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     if hasattr(dummy_draw, 
'textsize'):
 
   44         text_w, text_h = dummy_draw.textsize(text, font=pil_font)
 
   46         text_bbox = dummy_draw.textbbox((0,0), text, font=pil_font)
 
   47         text_w = text_bbox[2] - text_bbox[0]
 
   48         text_h = text_bbox[3] - text_bbox[1]
 
   49     text_bottom_offset = int(0.1 * text_h)
 
   52         offset_y = (text_h + text_bottom_offset) + offset_y
 
   56         raise NotImplementedError(
'loc {} not implemented.'.
format(loc))
 
   59     img_h, img_w = img.shape[:2]
 
   61     if not ((-text_w < x0 < img_w)
 
   62             and (-text_bottom_offset - text_h < y0 < img_h)):
 
   65     x1, y1 = max(x0, 0), max(y0, 0)
 
   66     x2 = min(x0+text_w, img_w)
 
   67     y2 = min(y0 + text_h + text_bottom_offset, img_h)
 
   77         (text_h + text_bottom_offset, text_w, 3),
 
   78         (0, 0, 0), dtype=np.uint8)
 
   79     if background_color 
is not None:
 
   80         img[y1:y2, x1:x2] = np.array(background_color, dtype=np.uint8)
 
   82     text_area[y1-y0:y2-y0, x1-x0:x2-x0] = img[y1:y2, x1:x2]
 
   85     if not (text_area.shape[0] == 0 
or text_area.shape[0] == 0):
 
   86         pil_img = Image.fromarray(text_area)
 
   87         draw = ImageDraw.Draw(pil_img)
 
   88         draw.text(xy=(0, 0), text=text, fill=color, font=pil_font)
 
   90         text_area = np.array(pil_img, dtype=np.uint8)
 
   91         img[y1:y2, x1:x2] = text_area[y1-y0:y2-y0, x1-x0:x2-x0]