Beispiel #1
0
 def write_text(cls,
                canvas: ImageDraw.Draw,
                fonts: 'FontsSize',
                text: str,
                pos: Optional[tuple] = (0, 0),
                *args: list,
                **kwargs: dict) -> tuple:
     x, y = pos
     lines_x = []
     text_x, text_y = 0, 0
     line_y = 0
     for char in text:
         if char == '\n':
             lines_x.append(text_x)
             x, y = (pos[0], y + line_y)
             text_x, text_y = (0, text_y + line_y)
             line_y = 0
             continue
         font, y_minus = fonts.detect(char)
         char_x, char_y = canvas.textsize(char, font=font)
         text_x += char_x
         if text_y < char_y:
             text_y = char_y
         if line_y < char_y:
             line_y = char_y
         canvas.text((x, y - y_minus), char, font=font, *args, **kwargs)
         x, y = ((x + char_x), y)
     final_x = max(lines_x) if lines_x else text_x
     final_y = text_y
     return final_x, final_y
def draw_text( data, text, color = 255, pos = 'lr' ):
    from PIL.Image import fromarray
    from PIL.ImageDraw import Draw
    from PIL import ImageFont
    from numpy import asarray

    font = ImageFont.load_default()

    image = fromarray( data )
    draw = Draw( image )
    w, h = draw.textsize( text, font = font )

    position = {
        'ul': lambda iw, ih, tw, th: ( 2, 0 ),
        'ur': lambda iw, ih, tw, th: ( iw - tw - 2, 0 ),
        'll': lambda iw, ih, tw, th: ( 2, ih - th ),
        'lr': lambda iw, ih, tw, th: ( iw - tw - 2, ih - th ),
    }

    pos = position[ pos ]( data.shape[ 1 ], data.shape[ 0 ], w, h )

    draw.text( pos, text, fill = color, font = font )
    del draw

    return asarray( image )
Beispiel #3
0
 def drawer(image, text):
     draw = Draw(image)
     char_images = []
     for c in text:
         font = random.choice(fonts)
         c_width, c_height = draw.textsize(c, font=font)
         c_height *= 2
         char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0))
         char_draw = Draw(char_image)
         char_draw.text((0, 0), c, font=font, fill=color())
         char_image = char_image.crop(char_image.getbbox())
         for drawing in drawings:
             char_image = drawing(char_image)
         char_images.append(char_image)
     width, height = image.size
     offset = int((width - sum(int(i.size[0] * squeeze_factor)
                               for i in char_images[:-1])
                   - char_images[-1].size[0]) / 2)
     for char_image in char_images:
         c_width, c_height = char_image.size
         mask = char_image.convert('L').point(lambda i: i * 1.97)
         image.paste(char_image,
                     (offset, int((height - c_height) / 2)),
                     mask)
         offset += int(c_width * squeeze_factor)
     return image
Beispiel #4
0
def draw_text(data, text, color=255, pos='lr'):
    from PIL.Image import fromarray
    from PIL.ImageDraw import Draw
    from PIL import ImageFont
    from numpy import asarray

    font = ImageFont.load_default()

    image = fromarray(data)
    draw = Draw(image)
    w, h = draw.textsize(text, font=font)

    position = {
        'ul': lambda iw, ih, tw, th: (2, 0),
        'ur': lambda iw, ih, tw, th: (iw - tw - 2, 0),
        'll': lambda iw, ih, tw, th: (2, ih - th),
        'lr': lambda iw, ih, tw, th: (iw - tw - 2, ih - th),
    }

    pos = position[pos](data.shape[1], data.shape[0], w, h)

    draw.text(pos, text, fill=color, font=font)
    del draw

    return asarray(image)
Beispiel #5
0
 def drawer(image_, text_):
     draw = Draw(image_)
     char_images = []
     for c_ in text_:
         font = random.choice(fonts)
         c_width, c_height = draw.textsize(c_, font=font)
         # char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0))
         o_width, o_height = font.getoffset(c_)
         char_image = Image.new(mode='RGB',
                                size=(c_width + o_width,
                                      c_height + o_height),
                                color=(0, 0, 0))
         char_draw = Draw(char_image)
         char_draw.text((0, 0), c_, font=font, fill=color())
         char_image = char_image.crop(char_image.getbbox())
         for drawing in drawings:
             char_image = drawing(char_image)
         char_images.append(char_image)
     width, height = image_.size
     offset_ = int(
         (width -
          sum(int(i.size[0] * squeeze_factor)
              for i in char_images[:-1]) - char_images[-1].size[0]) / 2)
     # 将单个字符图像画在验证码上
     for char_image in char_images:
         c_width, c_height = char_image.size
         mask = char_image.convert('L').point(lambda i: i * 1.97)
         image_.paste(char_image, (offset_, int((height - c_height) / 2)),
                      mask)
         offset_ += int(c_width * squeeze_factor)
     return image_
Beispiel #6
0
 def text(self, image, fonts, font_sizes=None, drawings=None, squeeze_factor=0.75, color=None):
     color = color if color else self._color
     fonts = tuple([truetype(name, size)
                    for name in fonts
                    for size in font_sizes or (65, 70, 75)])
     draw = Draw(image)
     char_images = []
     for c in self._text:
         font = random.choice(fonts)
         c_width, c_height = draw.textsize(c, font=font)
         char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0))
         char_draw = Draw(char_image)
         char_draw.text((0, 0), c, font=font, fill=color)
         char_image = char_image.crop(char_image.getbbox())
         for drawing in drawings:
             d = getattr(self, drawing)
             char_image = d(char_image)
         char_images.append(char_image)
     width, height = image.size
     offset = int((width - sum(int(i.size[0] * squeeze_factor)
                               for i in char_images[:-1]) -
                   char_images[-1].size[0]) / 2)
     for char_image in char_images:
         c_width, c_height = char_image.size
         mask = char_image.convert('L').point(lambda i: i * 1.97)
         image.paste(char_image,
                     (offset, int((height - c_height) / 2)),
                     mask)
         offset += int(c_width * squeeze_factor)
     return image
Beispiel #7
0
        def drawer(image, text):
            draw = Draw(image)
            char_images = []
            for c in text:
                font = random.choice(fonts)
                c_width, c_height = draw.textsize(c, font=font)
                char_image = Image.new('RGBA', (c_width + 1, c_height + 1),
                                       "black")
                char_draw = Draw(char_image)
                self._outline(char_draw, 0, 0, c, font, "gray", border)
                char_draw.text((0, 0), c, font=font, fill="black")

                char_image = char_image.crop(char_image.getbbox())
                for drawing in drawings:
                    char_image = drawing(char_image)
                char_image = char_image.resize((char_image.width, 42))
                char_images.append(char_image)
            width, height = image.size
            offset = int((width - sum(
                int(i.size[0] * squeeze_factor)
                for i in char_images[:-1]) - char_images[-1].size[0]) / 2)
            for char_image in char_images:
                c_width, c_height = char_image.size
                mask = char_image.convert('L').point(lambda i: i * 1.97)
                image.paste(char_image, (offset, int((height - c_height) / 2)),
                            mask)
                offset += int(c_width * squeeze_factor)
            self._remove_white_background_with_chops(image)
            return image
Beispiel #8
0
async def draw_player(
    draw: ImageDraw.Draw,
    composite: Image,
    player: Player,
    character: Image,
    rank: Image,
    y_offset: int,
) -> None:

    ready = is_ready if player.is_ready() else not_ready
    voice = voice_on if player.is_in_voice() else voice_off

    y_offset += PLAYER_ONE_START
    composite.paste(rank, (88, y_offset), rank)
    composite.paste(ready, (132, y_offset + 11), ready)
    composite.paste(voice, (155, y_offset + 5), voice)
    composite.paste(character, (183, y_offset))

    try:
        profile = await player.get_avatar()
        composite.paste(profile.resize((19, 19)), (226, y_offset + 8))
    except Exception:
        pass

    draw.text(
        (255, y_offset + 11),
        player.get_name(),
        font=name_font,
        fill=(81, 81, 81, 255),
    )
Beispiel #9
0
    def __imgBox(self, obj_list, image, im_width, im_height):
        im = image.convert('RGBA')
        drawn = Draw(im)
        fontsize = im_height * 0.01

        font = ImageFont.truetype('arial.ttf', int(round(fontsize)))

        coords = []

        for inst in obj_list:
            label = inst.tag_name
            probability = inst.probability

            x0, y0 = inst.bounding_box.left * im_width, inst.bounding_box.top * im_height
            x1, y1 = x0 + inst.bounding_box.width * im_width, y0 + inst.bounding_box.height * im_height
            xC, yC = abs(x0 + x1) / 2, abs(y0 + y1) / 2

            xC, yC = self.__img_to_drone_coords(xC, yC, im_width, im_height)

            coords.append((xC, yC))

            drawn.rectangle([(x0, y0), (x1, y1)], outline=(255, 0, 0, 255))
            drawn.text((x0, y0),
                       f'{label}: {round(probability, 3)}; ({xC}, {yC})',
                       fill=(0, 0, 0, 255),
                       font=font)

        return im, coords
Beispiel #10
0
 def text(self, image, fonts, font_sizes=None, drawings=None, squeeze_factor=0.75, color=None):
     color = color if color else self._color
     fonts = tuple([truetype(name, size)
                    for name in fonts
                    for size in font_sizes or (65, 70, 75)])
     draw = Draw(image)
     char_images = []
     for c in self._text:
         font = random.choice(fonts)
         c_width, c_height = draw.textsize(c, font=font)
         char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0))
         char_draw = Draw(char_image)
         char_draw.text((0, 0), c, font=font, fill=color)
         char_image = char_image.crop(char_image.getbbox())
         for drawing in drawings:
             d = getattr(self, drawing)
             char_image = d(char_image)
         char_images.append(char_image)
     width, height = image.size
     offset = int((width - sum(int(i.size[0] * squeeze_factor)
                               for i in char_images[:-1]) -
                   char_images[-1].size[0]) / 2)
     for char_image in char_images:
         c_width, c_height = char_image.size
         mask = char_image.convert('L').point(lambda i: i * 1.97)
         image.paste(char_image,
                     (offset, int((height - c_height) / 2)),
                     mask)
         offset += int(c_width * squeeze_factor)
     return image
Beispiel #11
0
  def generate_image_from_word(self, word, watermark=None, font_color=(140, 140, 140), background=(255, 255, 255, 0)):

    font_type = make_font_type(self.font_path, self.font_size)

    image_width = self.image_size[0]
    image_height = self.image_size[1]

    image = Image.new('RGBA', self.image_size, background)
    draw = Draw(image)

    # Draw the word.
    word_width, word_height = draw.textsize(word, font=font_type)
    width_offset = int((image_width - word_width) / 2)
    height_offset = int((image_height - word_height) / 2)
    draw.text((width_offset, height_offset), word, font=font_type, fill=font_color)

    # Do random distortion.
    image = np.asarray(image)
    image = elastic_transformations(image, alpha=1200, sigma=40)
    image = Image.fromarray(image)

    color = (112, 112, 112)
    self._create_noise_dots(image, color=color, n_min=450, n_max=500)
    self._create_noise_curves(image, color=color, width_min=1, width_max=3, n_min=8, n_max=12)

    if watermark:
      self._add_watermark(image, watermark, font_color=(112, 112, 112))

    image = image.convert('RGB')
    return image
Beispiel #12
0
def draw_text(text, font_spec, text_color, xy=None, anchor=None,
              box_color=None, box_padding=0, border_color=None, border_width=0,
              image=None):
    """Draws centered text on an image, optionally in a box."""

    draw = Draw(image)
    text_size = font_spec['size']
    font = ImageFont.truetype(font_spec['file'], size=text_size)

    # Measure the width of each character.
    character_widths = []
    for character in text:
        # Override the measured width, if specified.
        width_overrides = font_spec['width_overrides']
        if character in width_overrides.keys():
            character_width = width_overrides[character]
        else:
            character_width, _ = draw.textsize(character, font)
        character_widths.append(character_width)
    text_width = sum(character_widths)

    # If any xy is specified, use it.
    text_height = font_spec['height']
    if xy:
        x = xy[0] - text_width // 2
        y = xy[1] - text_height // 2

    # If any anchor is specified, adjust the xy.
    if anchor == 'center':
        x = image.width // 2 - text_width // 2
        y = image.height // 2 - text_height // 2
    elif anchor == 'center_x':
        x = image.width // 2 - text_width // 2
    elif anchor == 'center_y':
        y = image.height // 2 - text_height // 2
    elif anchor == 'bottom_right':
        x = image.width - box_padding - border_width - text_width
        y = image.height - box_padding - border_width - text_height

    # Draw the box background and border.
    box_xy = [x - box_padding,
              y - box_padding,
              x + text_width + box_padding,
              y + text_height + box_padding]
    border_xy = [box_xy[0] - border_width,
                 box_xy[1] - border_width,
                 box_xy[2] + border_width,
                 box_xy[3] + border_width]
    if border_color:
        draw.rectangle(border_xy, border_color)
    if box_color:
        draw.rectangle(box_xy, box_color)

    # Draw the text character by character.
    y -= font_spec['y_offset']
    for index in range(len(text)):
        character = text[index]
        draw.text((x, y), character, text_color, font)
        x += character_widths[index]
Beispiel #13
0
 def center_text(image, text, color, font):
   draw = Draw(image)
   width, height = image.size
   text_width, text_height = draw.textsize(text, font)
   position = (
     (width - text_width) / 2 + 100,
     ((height - (text_height * 1.5)) / 2)
   )
   draw.text(position, text, color, font)
   image.save("Assets\\PhilosophyImages\\temporary.png")
Beispiel #14
0
    def render(self, draw: ImageDraw.Draw):
        title = "SETUP MODE"
        id = self.states['deviceId']
        # Display Arm State
        w, h = draw.textsize(title)
        draw.text(((128 - w) / 2, (32 - h) / 2), title, font=font, fill=255)

        # Display Id
        w, h = draw.textsize(id)
        draw.text(((128 - w) / 2, 20), id, font=font, fill=255)
Beispiel #15
0
 def inimagehandler(self, code, message, params):
     im = new('RGBA', (int(params['width']), int(params['height'])))
     im.putalpha(new('1', (int(params['width']), int(params['height']))))
     draw = Draw(im)
     for count, line in enumerate(message.strip().split('\n')):
         draw.text((12, 15 * (count + 1)), line, fill='#000000')
     fh = StringIO()
     im.save(fh, PIL_TYPE_MAPPING[params['format']])
     fh.seek(0)
     return Response(params['format'], fh.read())
Beispiel #16
0
 def inimagehandler(self, code, message, params):
     im = new('RGBA', (int(params['width']), int(params['height'])))
     im.putalpha(new('1', (int(params['width']), int(params['height']))))
     draw = Draw(im)
     for count, line in enumerate(message.strip().split('\n')):
         draw.text((12,15*(count+1)), line, fill='#000000')
     fh = StringIO()
     im.save(fh, PIL_TYPE_MAPPING[params['format']])
     fh.seek(0)
     return Response(params['format'], fh.read())
Beispiel #17
0
 def inimagehandler(self, code, message, params):
     im = new("RGBA", (int(params["width"]), int(params["height"])))
     im.putalpha(new("1", (int(params["width"]), int(params["height"]))))
     draw = Draw(im)
     for count, line in enumerate(message.strip().split("\n")):
         draw.text((12, 15 * (count + 1)), line, fill="#000000")
     fh = StringIO()
     im.save(fh, PIL_TYPE_MAPPING[params["format"]])
     fh.seek(0)
     return Response(params["format"], fh.read())
Beispiel #18
0
  def _add_watermark(self, image, text, font_color=(140, 140, 140)):
    watermark_font_type = make_font_type(self.font_path, self.watermark_font_size)
    draw = Draw(image)
    w, h = draw.textsize(text, font=watermark_font_type)

    dx = (image.width - w) - 4.5
    dy = image.height - h - 0
    draw.text((dx, dy), text, font=watermark_font_type, fill=font_color)

    return image
Beispiel #19
0
    def get_classification(self, inp_image):
        """Determines the color of the traffic light in the image

        Args:
            image (cv::Mat): image containing the traffic light

        Returns:
            int: ID of traffic light color (specified in styx_msgs/TrafficLight)

        """
        image_array = np.array(inp_image)
        image = np.reshape(image_array,
                           (1, image_array.shape[0], image_array.shape[1],
                            image_array.shape[2]))
        results = self.sess.run(
            [
                self.graph.get_tensor_by_name('prefix/detection_boxes:0'),
                self.graph.get_tensor_by_name('prefix/detection_scores:0'),
                self.graph.get_tensor_by_name('prefix/detection_classes:0')
            ], {self.graph.get_tensor_by_name('prefix/image_tensor:0'): image})

        pilimg = Image.fromarray(image_array)
        classes = []
        for boxid in range(len(results[0][0])):
            if results[1][0][boxid] > 0.5:
                predclass = results[2][0][boxid]
                classes.append(predclass)
                if self.save_pred_images:
                    width = pilimg.size[0]
                    height = pilimg.size[1]
                    box = results[0][0][boxid]
                    xmin = int(box[1] * width)
                    ymin = int(box[0] * height)
                    xmax = int(box[3] * width)
                    ymax = int(box[2] * height)
                    draw = Draw(pilimg)
                    draw.rectangle([(xmin, ymin), (xmax, ymax)], outline='red')
                    draw.text((xmax + 5, ymin + 5),
                              "Class: " + str(self.class_map_str[predclass]),
                              font=self.font)

        if self.save_pred_images:
            pilimg.save(
                "/capstone/ros/classifier_output/bag/{:0>5d}.jpg".format(
                    self.prediction_counter))
            self.prediction_counter += 1

        if classes:
            keys = Counter(classes).keys()
            vals = Counter(classes).values()
            pred_class = keys[np.argmax(vals)]
            return self.class_map[pred_class]
        else:
            return TrafficLight.UNKNOWN
Beispiel #20
0
def gen_img(font_name, font_size, text, img_size):
    font = truetype(font_name + ".ttf", font_size)
    print(font.getsize("By"))
    width, height = img_size

    img = new("1", (width, height), 255)
    drawing = Draw(img)
    drawing.text((10, 10), text, fill=0, font=font)
    img = img.convert("L")
    img = np.asarray(img, dtype=np.uint8)
    return img
 def __draw_sticker_text(cur_sticker: Sticker, location_text_offset,
                         author_text_offset, draw_context: ImageDraw.Draw):
     draw_context.text(location_text_offset,
                       cur_sticker.location,
                       font=cur_sticker.font,
                       fill=cur_sticker.font_color,
                       draw_context=draw_context)
     draw_context.text(author_text_offset,
                       cur_sticker.author,
                       font=cur_sticker.font,
                       fill=cur_sticker.font_color,
                       draw_context=draw_context)
Beispiel #22
0
def draw_text_centered(draw: ImageDraw.Draw, xy: Tuple[int, int], text: str,
                       face: FontList):
    x, y = xy

    for font in face:
        width, _ = draw.textsize(text, font)
        if width <= 150:
            draw.text((x - width // 2, y - int(font.size / 1.7) + 1),
                      text,
                      font=font,
                      fill="black")
            return
Beispiel #23
0
 def fit(self, row_obj: dict, canvas: ImageDraw.Draw):
     """This function prints the text on image output.
     """
     rows, font_properties = self.create_row_with_slash(row_obj=row_obj)
     font, font_size = font_properties
     color = 0 if row_obj.get('font_color') >= 255 / 2 else 255
     x, y = row_obj.get('text_area')[0]
     shift_y = 0
     for row in rows:
         if len(row) - 1 > 0 and row[0] == ' ':
             row = row[1:]
         canvas.text((x - 1, y + shift_y), row, fill=color, font=font)
         shift_y += font_size + 5
Beispiel #24
0
    def _draw_date_box(self, draw: ImageDraw.Draw, top_left_corner: Tuple[int, int], width: int, date: datetime) -> int:
        """
        Draws a date/time clock onto the canvas at the given position.

        Args:
            draw: The ImageDraw instance to draw on the desired canvas.
            top_left_corner: Where to start the box.
            width: The fixed horizontal dimension of the box.
            date: The date/time to display on the clock.

        Returns:
            The bottom y coordinate of the box, so that further elements may be drawn after it
        """
        time_str = format_time(date, 'HH:mm', locale='pt_BR')
        time_font = self.fonts['huge']
        time_font_height = time_font.getsize('X')[1]

        date_str = format_date(date, "EEEE\ndd 'de' MMM 'de' yyyy", locale='pt_BR').capitalize()
        date_font = self.fonts['large']
        date_font_height = date_font.getsize('X')[1]

        margin = 20 * self.scaler_value

        bottom_y = int(top_left_corner[1] + time_font_height + date_font_height * 2 + margin * 4)
        draw.rectangle(
            (
                top_left_corner[0],
                top_left_corner[1],
                top_left_corner[0] + width,
                bottom_y
            ),
            fill=self.colors['date_box_background']
        )

        time_y = top_left_corner[1] + margin
        draw.text(
            (top_left_corner[0] + margin, time_y),
            time_str,
            fill=self.colors['date_box_text'],
            font=time_font,
        )

        draw.multiline_text(
            (top_left_corner[0] + margin, time_y + time_font_height + margin),
            date_str,
            fill=self.colors['date_box_text'],
            font=date_font
        )

        return bottom_y
Beispiel #25
0
def generate_letter(char, font_size, font_name):
    img_dim = (font_size + font_size / 2,) * 2
    img = new_image("RGB", img_dim, (0, 0, 0))
    img_draw = Draw(img)
    #font = PIL.ImageFont.ImageFont()
    #font.font = PIL.ImageFont.truetype(font_name, font_size)
    #font.color = tuple( [randrange(126, 256) for i in range(3)] )
    font = PIL.ImageFont.truetype(font_name, font_size)
    color = tuple( [randrange(126, 256) for i in range(3)] )
    img_draw.text((0, 0), char, color, font)
    #img = img_draw.flush()
    img = img.rotate(randrange(-30, 30), BICUBIC)
    mask = new_image("L", img.size, 0)
    mask.paste(img, (0, 0))
    return img, mask
Beispiel #26
0
    def draw(self,
             icon: Icon,
             size: Size = None,
             color: Color = '#000000',
             bg: Color = '#ffffff') -> PILImage:
        icon = self._normalize(icon)
        if size:
            font = self.font.font_variant(size=max(size))
        else:
            font = self.font
            size = (font.size, font.size)

        image = Image.new('RGBA', size, color_to_rgb(bg))
        draw = Draw(image)  # type: ImageDraw
        draw.text((0, 0), icon, fill=color_to_rgb(color), font=font)
        return image
Beispiel #27
0
 def DrawLapDuration(self, drw: ImageDraw.Draw):
     height = 125
     width = 225
     top = self._resolution[1] - height
     drw.rectangle(
         ((0, self._resolution[1] - height), (width, self._resolution[1])),
         fill=(0, 0, 0, 255))
     index = 0
     text_height = 40
     for lap_number, lap_duration_ms in self._lap_duration_queue[-3:]:
         drw.text(
             (0, top + (text_height * index)),
             '%s  %s' % (lap_number, _FormatLapDuration(lap_duration_ms)),
             font=self._font,
             fill=(0, 255, 0, 255))
         index += 1
Beispiel #28
0
def draw_text_relative_to_point(
    draw: ImageDraw.Draw,
    x: float,
    y: float,
    text: str,
    font: FreeTypeFont,
    color: str,
    axis=None,
):
    text_width, text_heigth = draw.textsize(text, font)
    if axis == "x":
        position = (x - text_width / 2, y)
    elif axis == "y":
        position = (x, y - text_heigth / 2)
    else:
        position = (x - text_width / 2, y - text_heigth / 2)
    draw.text(position, text, color, font=font)
Beispiel #29
0
    def create_noise_chars_without_mask(image, char, number):
        w, h = image.size
        font = truetype('../data/DroidSansMono.ttf', 30)
        draw = Draw(image)

        while number:
            x = random.randint(0, int(8 * w / 9))
            y = random.randint(0, int(7 * h / 10))

            color = random_color(10, 200, random.randint(220, 225))

            draw.text((x, y), char, fill=color, font=font)
            draw.text((x + 1, y + 1), char, fill=color, font=font)
            draw.text((x - 1, y - 1), char, fill=color, font=font)
            number -= 1

        return image
Beispiel #30
0
    def create_noise_chars_without_mask(image, char, number):
        w, h = image.size
        font = truetype(random.choice(DEFAULT_FONTS), 30)
        draw = Draw(image)

        while number:
            x = random.randint(0, int(8 * w / 9))
            y = random.randint(0, int(7 * h / 10))

            color = random_color(120, 220, random.randint(20, 55))

            draw.text((x, y), char, fill=color, font=font)
            draw.text((x + 1, y + 1), char, fill=color, font=font)
            draw.text((x - 1, y - 1), char, fill=color, font=font)
            number -= 1

        return image
Beispiel #31
0
    def plot_oriyolo(self, imgs, detections):
        detections = non_max_suppression(detections, self.opt.conf_thres,
                                         self.opt.nms_thres)
        toImg = transforms.ToPILImage()
        # we only show the image_batch[0]

        idx = []
        i = 0
        cls_name = ['car', 'person', 'fire']
        for detection in detections:
            if detection is not None:
                idx.append(i)
                i += 1

        if len(idx) == 0:
            self.viz.text('no bbox found with the conf_thres in %.2f' %
                          (self.opt.conf_thres),
                          win=1)
            return

        for i in idx:
            img = toImg(imgs[i, ...])
            ori_w, ori_h = img.size
            img = img.resize((270, 270))
            detection = detections[i]
            w, h = img.size
            draw = Draw(img)

            if detection is not None:
                for x1, y1, x2, y2, conf, cls_conf, cls_pred in detection:
                    x1 = float(x1) / ori_w * w
                    y1 = float(y1) / ori_h * h
                    x2 = float(x2) / ori_w * w
                    y2 = float(y2) / ori_h * h
                    x1 = max(0, int(x1))
                    y1 = max(0, int(y1))
                    x2 = min(int(x2), w)
                    y2 = min(int(y2), h)
                    draw.rectangle([(x1, y1), (x2, y2)], outline=(255, 0, 0))
                    #print(cls_pred)
                    name = cls_name[int(cls_pred)]
                    name += "=%.4f" % float(cls_conf)
                    f = ImageFont.truetype("fonts-japanese-gothic.ttf", 15)
                    draw.text((x1, y1), name, 'blue', font=f)
                self.viz.image(np.array(img).transpose((2, 0, 1)), win=i + 2)
Beispiel #32
0
 def show_all(self, draw: ImageDraw.Draw, last_sample: Sample,
              top_line: int) -> None:
     gap = (self.height - top_line) // len(self.PROBES)
     ypos = top_line
     for index, value in enumerate(last_sample.values):
         probe = self.PROBES[index]
         draw.text(((0, ypos)),
                   probe.name,
                   fill=self.PROBES[index].colour,
                   font=self.fonts[0].heading)
         valstr = self.value_str(probe, value)
         size = draw.textlength(valstr, font=self.fonts[0].body)
         xpos = self.width - size
         draw.text(((xpos, ypos)),
                   valstr,
                   fill=self.PROBES[index].colour,
                   font=self.fonts[0].body)
         ypos += gap
Beispiel #33
0
def antialiased_text(text: str,
                     font: ImageFont,
                     size_x: int,
                     size_y: int = None,
                     *,
                     offset_x: float = 1 / 2,
                     offset_y: float = 1 / 2,
                     wrap_width: int = 50,
                     msaa_size: int = 2,
                     **draw_kwargs) -> Image:
    """
    Returns a new image with antialiased text that you can then paste on your source image.

    Pillow has no support for antialiasing text so the way we achieve the same thing is
    creating an image multiple times larger and then resizing it with the antialias filter.

    :param text: The text to be written
    :param font: The font to be used
    :param size_x: The width of the desired image
    :param size_y: The height of the desired image
    :param offset_x: How far away from the top the text will be
    :param offset_y: How far away from the left the text will be
    :param draw_kwargs: Additional keyword arguments to the `draw` method
    :param wrap_width: The length at which strings should be wrapped
    :return: An image with the desired text
    """
    if size_y is None:
        size_y = size_x

    font = truetype(font.path, size=font.size * msaa_size)

    with Image.new('RGBA', (size_x * msaa_size, size_y * msaa_size)) as image:
        draw = Draw(image)

        for index, string in enumerate(textwrap.wrap(text, wrap_width),
                                       start=-1):
            width, height = font.getsize(string)
            pos = (size_x * msaa_size - width) / offset_x**-1, (
                size_y * msaa_size - height * -index) / offset_y**-1
            draw.text(pos, string, font=font, **draw_kwargs)

        return image.resize((size_x, size_y), resample=Image.ANTIALIAS)
def generate_capture(request):
    """
    You can visit the view with GET params like k, b, f to custom the capture.
    b indicates background color, and f foreground color.
    The value of color should be an integer, which will be convert to a hex color value. That is to say the value
     of a color should not be less than 0 or larger than 16777215.
    k indicates the key of the capture. It should exist in session before this view is visited, otherwise A 404 error
    will be throw out.
    And once the view is visited, the answer of the capture will be set a key in session which k indicates.
    """
    keyName, bcolor, fcolor = DEFAULT_CAPTURE_ID, DEFAULT_BACKGROUND, DEFAULT_FOREGROUND
    if 'k' in request.GET:
        if request.GET['k'] in request.session:
            keyName = request.GET['k']
        else:
            raise Http404()
    try:
        if 'b' in request.GET:
            bcolor = '#{:0>6.6s}'.format('%x' % max(min(int(request.GET['b']), 16777215), 0))
        if 'f' in request.GET:
            fcolor = '#{:0>6.6s}'.format('%x' % max(min(int(request.GET['f']), 16777215), 0))
    except:
        raise Http404()
    ver_fun = snippets[randint(0, len(snippets) - 1)]
    x, y = ver_fun[2](), ver_fun[3]()
    request.session[keyName] = '%r' % ver_fun[1](x, y)
    img = Image.new("RGB", (DEFAULT_WIDTH, DEFAULT_HEIGHT), bcolor)
    draw = Draw(img)
    font = ImageFont.truetype('font/SourceCodePro-Regular.ttf', DEFAULT_FONT_SIZE)
    for i in xrange(0, 3):
        draw.line([(0, randint(0, DEFAULT_HEIGHT)), (DEFAULT_WIDTH, randint(1, DEFAULT_HEIGHT))],
                  fill='#{:0>6.6s}'.format('%x' % randint(0, 16777215)))
    if x < 0:
        x = '(%s)' % x
    if y < 0:
        y = '(%s)' % y
    text = ver_fun[0] % (x, y)
    x, y = font.getsize(text)
    draw.text((DEFAULT_WIDTH / 2 - x / 2, DEFAULT_HEIGHT / 2 - y / 2), text, font=font, fill=fcolor)
    response = HttpResponse(mimetype='image/png')
    img.save(response, 'PNG')
    return response
Beispiel #35
0
    def paint(self, draw: ImageDraw.Draw, regions: RegionMap) -> None:
        sx, sy, ex, ey = self.region.poly.bounds
        font_size = 30
        factor = 0
        tries = 0

        while abs(factor - 1) > 0.05 and tries < 5:
            font = self.font('/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf',
                             font_size)
            w, h = draw.textsize(self.region.text, font=font)
            # TODO super random compromise betweeen fit to width and fit to height
            factor = 0.7 * (ex - sx) / w + 0.3 * (ey - sy) / h
            font_size = int(font_size * factor)
            tries += 1

        draw.text((sx, sy),
                  self.region.text,
                  fill=self.color,
                  font=font,
                  anchor="lt")
Beispiel #36
0
def load_chars(font_name, size, chars):
    """Load characters from given font of given size.

    :param font_name: given font name
    :param size: given size
    :param chars: given set of characters
    :return: dict of tuples - character: (image, max_match_val)
    """
    font = truetype(font_name + ".ttf", size)
    symbols = {}
    for char in chars:
        width, height = font.getsize(char)
        img = new("1", (width, height), 0)
        drawing = Draw(img)
        drawing.text((0, 0), char, fill=255, font=font)
        img = img.convert("L")
        img = np.asarray(img, dtype=np.uint8)
        if char != ' ':
            img = crop_text(img)
        symbols[char] = (img, match(img, img))
    return symbols
Beispiel #37
0
def mapdraw(args,colorbar):
   img = Image.new('RGB',(args['xlen'],args['ylen']),'white')
   draw = Draw(img)

   for key,value in args['datamap'].iteritems():
      draw.point(value,getrgb(str(key)))

   img2 = img.resize((args['y'],args['y']), Image.BILINEAR)

   imgclr = colorbar.resize((args['colorbar'],img2.size[1]), Image.BILINEAR)

   # ===== ENTIRE IMAGE CREATION W/ TEXT=====
   imgbox = Image.new('RGB',((300+args['y']+args['colorbar']),(img2.size[1]+200)),args['background'])
   imgbox.paste(img2,(100,100))
   imgbox.paste(imgclr,((200+img2.size[0]),100))

   drawbox = Draw(imgbox)
   title = args['title']
   titlesize = 50 # future user input
   font = truetype("/library/fonts/Arial.ttf",titlesize)
   smfontsize = 30 # future user input
   smfont = truetype("/library/fonts/Arial.ttf",smfontsize)
   titlewidth = font.getsize(title)[0]
   drawbox.text(((imgbox.size[0]/2 - titlewidth/2), titlesize/2),title,(0,0,0),font=font)

   drawbox.text(((imgbox.size[0] - 95),100),str(args['max']),(0,0,0),font=smfont)
   drawbox.text(((imgbox.size[0] - 95),(100 + img2.size[1] - smfontsize)),str(args['min']),(0,0,0),font=smfont)

   imgbox.show()
   if 'title' in args:
      title = args['title']+'_'+str(args['min'])+'_'+str(args['max'])+'.png'
   else:
      title = 'output_'+str(args['min'])+'_'+str(args['max'])+'.png'
   imgbox.save(args['save']+'/'+title)
 def draw_text_with_outline(self, draw: ImageDraw.Draw, text: str, x: float,
                            y: int, fnt: ImageFont.FreeTypeFont) -> None:
     draw.text((x - 2, y - 2), text, (0, 0, 0), font=fnt)
     draw.text((x + 2, y - 2), text, (0, 0, 0), font=fnt)
     draw.text((x + 2, y + 2), text, (0, 0, 0), font=fnt)
     draw.text((x - 2, y + 2), text, (0, 0, 0), font=fnt)
     draw.text((x, y), text, (255, 255, 255), font=fnt)
Beispiel #39
0
def draw_text(image, text, font_size):
    font = truetype(join(current_dir, 'static/font.ttf'), font_size)
    color = '#5C87B2'

    draw = Draw(image)
    char_images = []
    for ch in text:
        c_width, c_height = draw.textsize(ch, font=font)
        char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0))
        char_draw = Draw(char_image)
        char_draw.text((0, 0), ch, font=font, fill=color)
        char_image = char_image.crop(char_image.getbbox())
        char_images.append(char_image)

    width, height = image.size
    total = len(char_images)
    for i, char_image in enumerate(char_images):
        c_width, c_height = char_image.size
        mask = char_image.convert('L').point(lambda i: i * 1.97)
        upper = int((height - c_height) / 2)
        left = int((width * (i + 1) / (total + 1)) - c_width / 2)
        image.paste(char_image, (left, upper), mask)
    return image
Beispiel #40
0
    icon_height = 0

# Font laden und rausbekommen, wie gross der Button werden muss
ttf = '/Library/Fonts/Arial Narrow Bold.ttf'
font = truetype(ttf, 12, encoding='unic')
text_width, _ = font.getsize(label)
width = text_width + 2 * args.padding + icon_width

# jetzt den Hintergrund in den Button reinkopieren
button = Image.new('RGBA', (width, height * 2))
button.paste(background, (0, 0))
button.paste(flip(background), (0, height))
button.paste(right, (width-5, 0))
button.paste(flip(right), (width-5, height))

# das Icon muss auch rein, wenn wir eines haben
if icon:
    alpha_channel = icon.split()[3]
    mask = Image.eval(alpha_channel, lambda a: 255 if a >=128 else 0)
    for offs in [0, height]:
        button.paste(icon, (7, offs + int(height/2.0-icon_height/2.0)), mask)

# dann die Beschriftung reinmalen
draw = Draw(button)
draw.text((icon_width + args.padding, upper_text), label, font=font, fill=args.text_color)
draw.text((icon_width + args.padding, lower_text), label, font=font, fill=args.text_color)

# und schliesslich nur noch den Button speichern
#button.show()
button.save(filename, 'PNG')
Beispiel #41
0
    filename = 'button-small-%s.png' % label.lower().replace(' ', '-')

# Hintergrund zusammenbauen
gradients = Image.open('generate-button-small.png')
y = 0
height = 23
background = gradients.crop((0, y, 200, height))
right = gradients.crop((203, 0, 208, height))

# Font laden und rausbekommen, wie gross der Button werden muss
ttf = '/Library/Fonts/Arial Narrow Bold.ttf'
font = truetype(ttf, 12, encoding='unic')
text_width, _ = font.getsize(label)
width = text_width + 2 * args.padding

# jetzt den Hintergrund in den Button reinkopieren
button = Image.new('RGBA', (width, height * 2))
button.paste(background, (0, 0))
button.paste(flip(background), (0, height))
button.paste(right, (width-5, 0))
button.paste(flip(right), (width-5, height))

# dann die Beschriftung reinmalen
draw = Draw(button)
draw.text((args.padding, 0+3), label, font=font, fill=args.text_color)
draw.text((args.padding, 23+4), label, font=font, fill=args.text_color)

# und schliesslich nur noch den Button speichern
#button.show()
button.save(filename, 'PNG')