5 from PIL
import ImageDraw
6 from PIL
import ImageFont
10 img, text, pos, font_path, font_size, color, background_color=None,
11 offset_x=0, offset_y=0, loc='top'):
12 """Put text to image using pillow.
14 You can put text to an image including non-ASCII characters.
30 background_color : tuple(int) or None
31 background color in text area. If this value is None, do nothing.
39 if sys.version_info < (3, 0):
40 text = text.decode(
'utf-8')
41 pil_font = ImageFont.truetype(font=font_path, size=font_size)
42 dummy_draw = ImageDraw.Draw(Image.new(
"RGB", (0, 0)))
43 text_w, text_h = dummy_draw.textsize(text, font=pil_font)
44 text_bottom_offset = int(0.1 * text_h)
47 offset_y = (text_h + text_bottom_offset) + offset_y
51 raise NotImplementedError(
'loc {} not implemented.'.
format(loc))
54 img_h, img_w = img.shape[:2]
56 if not ((-text_w < x0 < img_w)
57 and (-text_bottom_offset - text_h < y0 < img_h)):
60 x1, y1 = max(x0, 0), max(y0, 0)
61 x2 = min(x0+text_w, img_w)
62 y2 = min(y0 + text_h + text_bottom_offset, img_h)
72 (text_h + text_bottom_offset, text_w, 3),
73 (0, 0, 0), dtype=np.uint8)
74 if background_color
is not None:
75 img[y1:y2, x1:x2] = np.array(background_color, dtype=np.uint8)
77 text_area[y1-y0:y2-y0, x1-x0:x2-x0] = img[y1:y2, x1:x2]
80 if not (text_area.shape[0] == 0
or text_area.shape[0] == 0):
81 pil_img = Image.fromarray(text_area)
82 draw = ImageDraw.Draw(pil_img)
83 draw.text(xy=(0, 0), text=text, fill=color, font=pil_font)
85 text_area = np.array(pil_img, dtype=np.uint8)
86 img[y1:y2, x1:x2] = text_area[y1-y0:y2-y0, x1-x0:x2-x0]