Python PIL.ImageFont.load_default() Examples

The following are 30 code examples of PIL.ImageFont.load_default(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PIL.ImageFont , or try the search function .
Example #1
Source File: ppm_utils.py    From avocado-vt with GNU General Public License v2.0 7 votes vote down vote up
def add_timestamp(image, timestamp, margin=2):
    """
    Return an image object with timestamp bar added at the bottom.

    param image: pillow image object
    param timestamp: timestamp in seconds since the Epoch
    param margin: timestamp margin, default is 2
    """
    width, height = image.size
    font = ImageFont.load_default()
    watermark = time.strftime('%c', time.localtime(timestamp))
    # bar height = text height + top margin + bottom margin
    bar_height = font.getsize(watermark)[1] + 2 * margin

    # place bar at the bottom
    new_image = ImageOps.expand(image, border=(0, 0, 0, bar_height),
                                fill='lightgrey')
    draw = ImageDraw.Draw(new_image)
    # place timestamp at the left side of the bar
    x, y = margin, height + margin
    draw.text((x, y), watermark, font=font, fill='black')
    return new_image 
Example #2
Source File: VWWeather.py    From VisorWare with GNU Affero General Public License v3.0 6 votes vote down vote up
def weather(debugStatus):
    print("Starting live weather stream...")
    TempDisp = 1
    HumidDisp = 0
    while GPIO.input(homeb) == True:
        font = ImageFont.load_default()        
        url = "http://api.openweathermap.org/data/2.5/weather?id=524901&APPID=6d711345f94972e7ac62fc8f43cc648c&lat=24.19&lon=55.76"
        fetched_data = requests.get(url)
        fetched_data_json = fetched_data.json()
        main_data = fetched_data_json.get('main')
        current_tempK = main_data.get('temp')
        current_humidity = main_data.get('humidity')
        current_temp = round(current_tempK - 273, 1)
        CurrTemp = int(current_temp)
        FinalTemp = "Temperature: " + (str(current_temp))
        FinalHumid = "Humidity: " + (str(current_humidity))

        VisionEngine.disptext(FinalTemp, FinalHumid, " ", " ",0,0,0,0, 0, 12,24,36, debugStatus, '0') 
Example #3
Source File: vcsi.py    From vcsi with MIT License 6 votes vote down vote up
def load_font(args, font_path, font_size, default_font_path):
    """Loads given font and defaults to fallback fonts if that fails."""
    if args.is_verbose:
        print("Loading font...")

    fonts = [font_path] + FALLBACK_FONTS
    if font_path == default_font_path:
        for font in fonts:
            if args.is_verbose:
                print("Trying to load font:", font)
            if os.path.exists(font):
                try:
                    return ImageFont.truetype(font, font_size)
                except OSError:
                    pass
        print("Falling back to default font.")
        return ImageFont.load_default()
    else:
        try:
            return ImageFont.truetype(font_path, font_size)
        except OSError:
            error_exit("Cannot load font: {}".format(font_path)) 
Example #4
Source File: __init__.py    From CNCGToolKit with MIT License 6 votes vote down vote up
def generate(cls, size, string, filetype="JPEG"):
        """
            Generates a squared avatar with random background color.

            :param size: size of the avatar, in pixels
            :param string: string to be used to print text and seed the random
            :param filetype: the file format of the image (i.e. JPEG, PNG)
        """
        render_size = max(size, Avatar.MIN_RENDER_SIZE)
        image = Image.new('RGB', (render_size, render_size),
                          cls._background_color(string))
        draw = ImageDraw.Draw(image)
        # font = cls._font(render_size)
        font = ImageFont.load_default()
        text = cls._text(string)
        draw.text(cls._text_position(render_size, text, font),
                  text,
                  fill=cls.FONT_COLOR,
                  font=font)
        stream = BytesIO()
        image = image.resize((size, size), Image.ANTIALIAS)
        image.save(stream, format=filetype, optimize=True)
        return stream.getvalue() 
Example #5
Source File: watermarking_pdf.py    From Python-Automation-Cookbook with MIT License 6 votes vote down vote up
def create_watermark(watermarked_by):
    print('Creating a watermark')
    mask = Image.new('L', WATERMARK_SIZE, 0)
    draw = ImageDraw.Draw(mask)
    font = ImageFont.load_default()
    text = 'WATERMARKED BY {}\n{}'.format(watermarked_by, datetime.now())
    draw.multiline_text((0, 100), text, 55, font=font)

    watermark = Image.new('RGB', WATERMARK_SIZE)
    watermark.putalpha(mask)
    watermark = watermark.resize((1950, 1950))
    watermark = watermark.rotate(45)
    # Crop to only the watermark
    bbox = watermark.getbbox()
    watermark = watermark.crop(bbox)

    return watermark 
Example #6
Source File: summary.py    From tensorboardX with MIT License 6 votes vote down vote up
def _draw_single_box(image, xmin, ymin, xmax, ymax, display_str, color='black', color_text='black', thickness=2):
    from PIL import ImageDraw, ImageFont
    font = ImageFont.load_default()
    draw = ImageDraw.Draw(image)
    (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
    draw.line([(left, top), (left, bottom), (right, bottom),
               (right, top), (left, top)], width=thickness, fill=color)
    if display_str:
        text_bottom = bottom
        # Reverse list and print from bottom to top.
        text_width, text_height = font.getsize(display_str)
        margin = np.ceil(0.05 * text_height)
        draw.rectangle(
            [(left, text_bottom - text_height - 2 * margin),
             (left + text_width, text_bottom)], fill=color
        )
        draw.text(
            (left + margin, text_bottom - text_height - margin),
            display_str, fill=color_text, font=font
        )
    return image 
Example #7
Source File: summary.py    From tensorboardX with MIT License 6 votes vote down vote up
def _draw_single_box(image, xmin, ymin, xmax, ymax, display_str, color='black', color_text='black', thickness=2):
    from PIL import ImageDraw, ImageFont
    font = ImageFont.load_default()
    draw = ImageDraw.Draw(image)
    (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
    draw.line([(left, top), (left, bottom), (right, bottom),
               (right, top), (left, top)], width=thickness, fill=color)
    if display_str:
        text_bottom = bottom
        # Reverse list and print from bottom to top.
        text_width, text_height = font.getsize(display_str)
        margin = np.ceil(0.05 * text_height)
        draw.rectangle(
            [(left, text_bottom - text_height - 2 * margin),
             (left + text_width, text_bottom)], fill=color
        )
        draw.text(
            (left + margin, text_bottom - text_height - margin),
            display_str, fill=color_text, font=font
        )
    return image 
Example #8
Source File: utils.py    From PythonHomework with MIT License 6 votes vote down vote up
def draw_text(
    img: Image,
    text: str,
    location: tuple = (0, 0),
    text_color=(0, 0, 0)
) -> Image:
    draw = ImageDraw.Draw(img)

    try:
        # For Linux
        font = ImageFont.truetype("DejaVuSans.ttf", 20)
    except Exception:
        logger.warning("No font DejaVuSans; use default instead")
        # For others
        font = ImageFont.load_default()
    draw.text(location, text, font=font, fill=text_color)
    return img 
Example #9
Source File: detection_3d_metrics.py    From lingvo with Apache License 2.0 5 votes vote down vote up
def DrawDifficulty(self, images, gt_bboxes, gt_box_weights, difficulties):
    """Draw the difficulty values on each ground truth box."""
    batch_size = np.shape(images)[0]
    try:
      font = ImageFont.truetype('arial.ttf', size=20)
    except IOError:
      font = ImageFont.load_default()

    for batch_id in range(batch_size):
      image = images[batch_id, :, :, :]
      original_image = image
      image = Image.fromarray(np.uint8(original_image)).convert('RGB')
      draw = ImageDraw.Draw(image)
      difficulty_vector = difficulties[batch_id]
      box_data = gt_bboxes[batch_id]

      for box_id in range(box_data.shape[0]):
        box_weight = gt_box_weights[batch_id, box_id]
        if box_weight == 0:
          continue
        center_x = box_data[box_id, 0]
        center_y = box_data[box_id, 1]
        difficulty_value = str(difficulty_vector[box_id])

        # Draw a rectangle background slightly larger than the text.
        text_width, text_height = font.getsize(difficulty_value)
        draw.rectangle(
            [(center_x - text_width / 1.8, center_y - text_height / 1.8),
             (center_x + text_width / 1.8, center_y + text_height / 1.8)],
            fill='darkcyan')

        # Center the text in the rectangle
        draw.text((center_x - text_width / 2, center_y - text_height / 2),
                  str(difficulty_value),
                  fill='lightcyan',
                  font=font)
      np.copyto(original_image, np.array(image)) 
Example #10
Source File: visualization_utils.py    From mtl-ssl with Apache License 2.0 5 votes vote down vote up
def put_text_on_image(image,
                      text,
                      left=0.0,
                      top=0.0,
                      color='white',
                      use_normalized_coordinates=True,
                      font_size=24):
  draw = ImageDraw.Draw(image)
  im_width, im_height = image.size

  font_path = '../../fonts/Ubuntu Mono derivative Powerline.ttf'
  try:
    font = ImageFont.truetype(font_path, font_size)
  except IOError:
    font = ImageFont.load_default()

  text_width, text_height = font.getsize(text)
  margin = np.ceil(0.05 * text_height)
  draw.rectangle(
      [(left, top), (left + text_width, top + text_height + 2 * margin)],
      fill=color)
  draw.text(
      (left + margin, top + margin),
      text,
      fill='black',
      font=font) 
Example #11
Source File: utils.py    From nider with MIT License 5 votes vote down vote up
def get_font(fontfullpath, fontsize):
    '''Function to create a truetype ``PIL.ImageFont`` that provides fallbacks for invalid arguments

    Args:
        fontfullpath (str): path to the desired font.
        fontsize (int): size of the font.

    Returns:
        PIL.ImageFont: Default PIL ImageFont if ``fontfullpath`` is either unreachable or provided ``fontfullpath`` is ``None``.

    Raises:
        nider.exceptions.DefaultFontWarning: if ``fontfullpath`` is ``None``.
        nider.exceptions.FontNotFoundWarning: if ``fontfullpath`` does not exist.
    '''
    if fontfullpath is None:
        warnings.warn(DefaultFontWarning())
        font = ImageFont.load_default()
        font.is_default = True
    elif not os.path.exists(fontfullpath):
        warnings.warn(FontNotFoundWarning(fontfullpath))
        font = ImageFont.load_default()
        font.is_default = True
    else:
        font = ImageFont.truetype(fontfullpath, fontsize)
        font.is_default = False
    return font 
Example #12
Source File: text.py    From DeepFaceLab with GNU General Public License v3.0 5 votes vote down vote up
def _get_pil_font (font, size):
    global pil_fonts
    try:
        font_str_id = '%s_%d' % (font, size)
        if font_str_id not in pil_fonts.keys():
            pil_fonts[font_str_id] = ImageFont.truetype(font + ".ttf", size=size, encoding="unic")
        pil_font = pil_fonts[font_str_id]
        return pil_font
    except:
        return ImageFont.load_default() 
Example #13
Source File: OpenMV-I2C.py    From OpenTracker with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
                self.ser = serial.Serial(port='/dev/ttyAMA0',baudrate=9600, timeout = 0.2)
                # Raspberry Pi pin configuration:
                RST = 24
                # Note the following are only used with SPI:
                DC = 23
                SPI_PORT = 0
                SPI_DEVICE = 0
                # 128x32 display with hardware I2C:
                #self.disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
                # 128x64 display with hardware I2C:
                self.disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
                # Initialize library.
                self.disp.begin()

                # Clear display.
                self.disp.clear()
                self.disp.display()

                # Create blank image for drawing.
                # Make sure to create image with mode '1' for 1-bit color.
                width = self.disp.width
                height = self.disp.height
                self.image = Image.new('1', (width, height))

                # Get drawing object to draw on image.
                self.draw = ImageDraw.Draw(self.image)
                padding = 2
                shape_width = 20
                top = padding
                bottom = height-padding
                x = padding
                x += shape_width+padding

                # Load default font.
                #self.font = ImageFont.load_default()
                self.font = ImageFont.truetype('Minecraftia-Regular.ttf', 8) 
Example #14
Source File: __init__.py    From GW2Bot with MIT License 5 votes vote down vote up
def __init__(self, bot):
        self.bot = bot
        self.db = self.bot.database.db.gw2
        with open("cogs/guildwars2/gamedata.json", encoding="utf-8",
                  mode="r") as f:
            self.gamedata = json.load(f)
        self.session = bot.session
        self.boss_schedule = self.generate_schedule()
        self.embed_color = 0xc12d2b
        self.log = logging.getLogger(__name__)
        self.tasks = []
        self.waiting_for = []
        self.emojis = {}
        self.chatcode_preview_opted_out_guilds = set()
        try:
            self.font = ImageFont.truetype("GWTwoFont1p1.ttf", size=30)
        except IOError:
            self.font = ImageFont.load_default()
        setup_tasks = [
            self.prepare_emojis, self.prepare_linkpreview_guild_cache
        ]
        for task in setup_tasks:
            bot.loop.create_task(task())
        self.tasks = [
            self.game_update_checker, self.daily_checker, self.news_checker,
            self.gem_tracker, self.world_population_checker,
            self.guild_synchronizer, self.boss_notifier,
            self.forced_account_names, self.event_reminder_task,
            self.worldsync_task
        ]
        for task in self.tasks:
            task.start() 
Example #15
Source File: MapFetchHandler.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def __create_no_data(width, height):

        if MapFetchHandler.NO_DATA_IMAGE is None:
            img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
            draw = ImageDraw.Draw(img)

            fnt = ImageFont.load_default()

            for x in range(10, width, 100):
                for y in range(10, height, 100):
                    draw.text((x, y), "NO DATA", (180, 180, 180), font=fnt)
            MapFetchHandler.NO_DATA_IMAGE = img

        return MapFetchHandler.NO_DATA_IMAGE 
Example #16
Source File: cw_pil.py    From pycoast with GNU General Public License v3.0 5 votes vote down vote up
def _get_font(self, outline, font_file, font_size):
        """Return a font."""
        if font_file is None:
            return ImageFont.load_default()
        return ImageFont.truetype(font_file, font_size) 
Example #17
Source File: utils.py    From keras-vis with MIT License 5 votes vote down vote up
def draw_text(img, text, position=(10, 10), font='FreeSans.ttf', font_size=14, color=(0, 0, 0)):
    """Draws text over the image. Requires PIL.

    Args:
        img: The image to use.
        text: The text string to overlay.
        position: The text (x, y) position. (Default value = (10, 10))
        font: The ttf or open type font to use. (Default value = 'FreeSans.ttf')
        font_size: The text font size. (Default value = 12)
        color: The (r, g, b) values for text color. (Default value = (0, 0, 0))

    Returns: Image overlayed with text.
    """
    _check_pil()

    font_files = _find_font_file(font)
    if len(font_files) == 0:
        logger.warn("Failed to lookup font '{}', falling back to default".format(font))
        font = ImageFont.load_default()
    else:
        font = ImageFont.truetype(font_files[0], font_size)

    # Don't mutate original image
    img = Image.fromarray(img)
    draw = ImageDraw.Draw(img)
    draw.text(position, text, fill=color, font=font)
    return np.asarray(img) 
Example #18
Source File: object_detection.py    From aiexamples with Apache License 2.0 5 votes vote down vote up
def draw_boxes(image, boxes, class_names, scores, max_boxes=10, min_score=0.1):
  """Overlay labeled boxes on an image with formatted scores and label names."""
  colors = list(ImageColor.colormap.values())

  try:
    font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Regular.ttf",
                              25)
  except IOError:
    print("Font not found, using default font.")
    font = ImageFont.load_default()

  for i in range(min(boxes.shape[0], max_boxes)):
    if scores[i] >= min_score:
      ymin, xmin, ymax, xmax = tuple(boxes[i].tolist())
      display_str = "{}: {}%".format(class_names[i].decode("ascii"),
                                     int(100 * scores[i]))
      color = colors[hash(class_names[i]) % len(colors)]
      image_pil = Image.fromarray(np.uint8(image)).convert("RGB")
      draw_bounding_box_on_image(
          image_pil,
          ymin,
          xmin,
          ymax,
          xmax,
          color,
          font,
          display_str_list=[display_str])
      np.copyto(image, np.array(image_pil))
  return image 
Example #19
Source File: test_imagefont.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_unicode_pilfont(self):
        # should not segfault, should return UnicodeDecodeError
        # issue #2826
        font = ImageFont.load_default()
        with self.assertRaises(UnicodeEncodeError):
            font.getsize(u"’") 
Example #20
Source File: test_imagefont.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_default_font(self):
        # Arrange
        txt = 'This is a "better than nothing" default font.'
        im = Image.new(mode='RGB', size=(300, 100))
        draw = ImageDraw.Draw(im)

        target = 'Tests/images/default_font.png'
        target_img = Image.open(target)

        # Act
        default_font = ImageFont.load_default()
        draw.text((10, 10), txt, font=default_font)

        # Assert
        self.assert_image_equal(im, target_img) 
Example #21
Source File: test_font_leaks.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_leak(self):
        default_font = ImageFont.load_default()
        self._test_font(default_font) 
Example #22
Source File: utils.py    From pytorch-0.4-yolov3 with MIT License 5 votes vote down vote up
def drawtext(img, pos, text, bgcolor=(255,255,255), font=None):
    if font is None:
        font = ImageFont.load_default().font
    (tw, th) = font.getsize(text)
    box_img = Image.new('RGB', (tw+2, th+2), bgcolor)
    ImageDraw.Draw(box_img).text((0, 0), text, fill=(0,0,0,255), font=font)
    if img.mode != 'RGB':
        img = img.convert('RGB')
    sx, sy = int(pos[0]),int(pos[1]-th-2)
    if sx<0:
        sx=0
    if sy<0:
        sy=0
    img.paste(box_img, (sx, sy)) 
Example #23
Source File: visualize.py    From tiny-faces-pytorch with MIT License 5 votes vote down vote up
def draw_bounding_box(img, bbox, labels):
    draw = ImageDraw.Draw(img)
    font = ImageFont.load_default()
    color = tuple(np.random.choice(range(100, 256), size=3))

    draw.rectangle((bbox[0], bbox[1], bbox[2], bbox[3]), outline=color)

    for i, k in enumerate(labels.keys()):
        w, h = font.getsize(labels[k])
        # draw.rectangle((bbox[0], bbox[1] + i*h, bbox[0] + w, bbox[1] + (i+2)*h), fill=color)
        draw.text((bbox[0], bbox[1] + i*h), "{0}:{1:.3} ".format(k, labels[k]), fill=color)

    return img 
Example #24
Source File: visualisation.py    From tsinfer with GNU General Public License v3.0 5 votes vote down vote up
def draw_copying_path(self, filename, child_row, parents, breakpoints):
        origin = self.haplotype_origin
        b = self.box_size
        m = self.num_sites
        image = self.base_image.copy()
        draw = ImageDraw.Draw(image)
        y = self.row_map[child_row] * b + origin[1]
        x = origin[0]
        draw.rectangle(
            [(x, y), (x + m * b, y + b)], outline=self.copying_outline_colour
        )
        for k in range(m):
            if parents[k] != -1:
                row = self.row_map[parents[k]]
                y = row * b + origin[1]
                x = k * b + origin[0]
                a = self.ancestors[parents[k], k]
                draw.rectangle([(x, y), (x + b, y + b)], fill=self.copy_colours[a])

        for position in breakpoints:
            x = self.x_coordinate_map[position]
            y1 = origin[0] + self.row_map[0] * b
            y2 = origin[1] + (self.row_map[len(self.row_map) - 1] + 1) * b
            draw.line([(x, y1), (x, y2)], fill="black")

        # Draw the positions of the sites.
        font = ImageFont.load_default()
        for site in self.original_ts.sites():
            label = "{} {:.6f}".format(site.id, site.position)
            img_txt = Image.new("L", font.getsize(label), color="white")
            draw_txt = ImageDraw.Draw(img_txt)
            draw_txt.text((0, 0), label, font=font)
            t = img_txt.rotate(90, expand=1)
            x = origin[0] + site.id * b
            y = origin[1] - b
            image.paste(t, (x, y))
        # print("Saving", filename)
        image.save(filename) 
Example #25
Source File: util.py    From flask-restful-example with MIT License 5 votes vote down vote up
def __init__(self, width=50, height=12):

        self.width = width
        self.height = height
        # 新图片对象
        self.im = Image.new('RGB', (width, height), 'white')
        # 字体
        self.font = ImageFont.load_default()
        # draw对象
        self.draw = ImageDraw.Draw(self.im) 
Example #26
Source File: visualization.py    From bop_toolkit with MIT License 5 votes vote down vote up
def write_text_on_image(im, txt_list, loc=(3, 0), color=(1.0, 1.0, 1.0),
                        size=20):
  """Writes text info on an image.

  :param im: ndarray on which the text info will be written.
  :param txt_list: List of dictionaries, each describing one info line:
    - 'name': Entry name.
    - 'val': Entry value.
    - 'fmt': String format for the value.
  :param loc: Location of the top left corner of the text box.
  :param color: Font color.
  :param size: Font size.
  :return: Image with written text info.
  """
  im_pil = Image.fromarray(im)

  # Load font.
  try:
    font_path = os.path.join(os.path.dirname(__file__), 'droid_sans_mono.ttf')
    font = ImageFont.truetype(font_path, size)
  except IOError:
    misc.log('Warning: Loading a fallback font.')
    font = ImageFont.load_default()

  draw = ImageDraw.Draw(im_pil)
  for info in txt_list:
    if info['name'] != '':
      txt_tpl = '{}:{' + info['fmt'] + '}'
    else:
      txt_tpl = '{}{' + info['fmt'] + '}'
    txt = txt_tpl.format(info['name'], info['val'])
    draw.text(loc, txt, fill=tuple([int(c * 255) for c in color]), font=font)
    text_width, text_height = font.getsize(txt)
    loc = (loc[0], loc[1] + text_height)
  del draw

  return np.array(im_pil) 
Example #27
Source File: gauge.py    From Reinforcement-Learning-for-Self-Driving-Cars with Apache License 2.0 5 votes vote down vote up
def get_font(font_path, font_size):
    try:
        font = ImageFont.truetype(font_path, font_size)
    except IOError:
        font = ImageFont.load_default()

    return font 
Example #28
Source File: b06902079.py    From PythonHomework with MIT License 5 votes vote down vote up
def task_8(
    img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
    '''
    Task 8: Module

    Args:
        img_url: address of an image

    Returns:
        result_img: an PIL Image

    Hints:
        * Make sure you have installed the PIL package
        * Take a look at utils.py first
        * You could easily find answers with Google
    '''
    from PIL import Image, ImageFont, ImageDraw
    from urllib import request
    result_img = Image.open(request.urlopen(img_url))
    draw = ImageDraw.Draw(result_img)
    font = ImageFont.load_default().font
    draw.text((0, 0), "B06902079", (0, 0, 0), font=font)
    # TODO: download the image from img_url with the request module
    # and add your student ID on it with draw_name() in the utils module
    # under src/.

    # You are allowed to change the img_url to your own image URL.

    # Display the image:
    # result_img.show()
    # Note: please comment this line when hand in.

    # If you are running on a server, use
    # result.save('test.jpg')
    # and copy the file to local or use Jupyter Notebook to render.

    # End of TODO

    return result_img 
Example #29
Source File: txt_to_img.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def text_to_png(text, color = "#000", bgcolor = "#FFF", fontfullpath = None, fontsize = 13, leftpadding = 3, rightpadding = 3, width = 500):
	REPLACEMENT_CHARACTER = 'nlnlnl'
	NEWLINE_REPLACEMENT_STRING = ' ' + REPLACEMENT_CHARACTER + ' '


	font = ImageFont.load_default() if fontfullpath == None else ImageFont.truetype(fontfullpath, fontsize)
	text = text.replace('\n', NEWLINE_REPLACEMENT_STRING)

	lines = []
	line = ""

	for word in text.split():
		if word == REPLACEMENT_CHARACTER: #give a blank line
			lines.append( line[1:] ) #slice the white space in the begining of the line
			line = ""
			lines.append( "" ) #the blank line
		elif font.getsize( line + ' ' + word )[0] <= (width - rightpadding - leftpadding):
			line += ' ' + word
		else: #start a new line
			lines.append( line[1:] ) #slice the white space in the begining of the line
			line = ""

			#TODO: handle too long words at this point
			line += ' ' + word #for now, assume no word alone can exceed the line width

	if len(line) != 0:
		lines.append( line[1:] ) #add the last line

	line_height = font.getsize(text)[1]
	img_height = line_height * (len(lines) + 1)

	img = Image.new("RGBA", (width, img_height), bgcolor)
	draw = ImageDraw.Draw(img)

	y = 0
	for line in lines:
		draw.text( (leftpadding, y), line, color, font=font)
		y += line_height

	byte_io = BytesIO()
	img.save(byte_io, 'PNG')
	byte_io.seek(0)
	return byte_io.read()

# #show time
# text2png(u"This is\na\ntest şğıöç zaa xd ve lorem hipster", 'test.png', fontfullpath = "font.ttf") 
Example #30
Source File: Visualization.py    From VehicleDetectionAndTracking with GNU General Public License v3.0 4 votes vote down vote up
def draw_bounding_box_on_image(image, ymin, xmin, ymax, xmax, center, color='red', thickness=4, display_str_list=(),
                               use_normalized_coordinates=True):
    """
    :param image: A numpy array with shape [height, width, 3]
    :param ymin: ymin of bounding box
    :param xmin: xmin of bounding box
    :param ymax: ymax of bounding box
    :param xmax: xmax of bounding box
    :param color: Color to draw bounding box
    :param thickness: Line thickness
    :param display_str_list: List of strings to display in box (each to be shown on its own line)
    :param use_normalized_coordinates: If True, treat coordinates ymin, xmin, ymax, xmax as relative to the image.
        Otherwise treat coordinates as absolute
    """
    draw = ImageDraw.Draw(image)
    im_width, im_height = image.size

    if use_normalized_coordinates:
        (left, right, top, bottom) = (xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height)
    else:
        (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
    draw.line([(left, top), (left, bottom), (right, bottom), (right, top), (left, top)], width=thickness, fill=color)

    try:
        font = ImageFont.truetype('arial.ttf', 24)
    except IOError:
        font = ImageFont.load_default()

    # If the total height of the display strings added to the top of the bounding box exceeds the top of the image,
    # stack the strings below the bounding box instead of above.
    display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]
    # Each display_str has a top and bottom margin of 0.05x.
    total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)

    if top > total_display_str_height:
        text_bottom = top
    else:
        text_bottom = bottom + total_display_str_height

    # Reverse list and print from bottom to top.
    for display_str in display_str_list[::-1]:
        text_width, text_height = font.getsize(display_str)
        margin = np.ceil(0.05 * text_height)
        draw.rectangle([(left, text_bottom - text_height - 2 * margin), (left + text_width, text_bottom)], fill=color)
        draw.text((left + margin, text_bottom - text_height - margin), display_str, fill='black', font=font)
        text_bottom -= text_height - 2 * margin


# Method: Used to draw keypoints on an image (numpy array)