put_text.py
Go to the documentation of this file.
1 import sys
2 
3 import numpy as np
4 from PIL import Image
5 from PIL import ImageDraw
6 from PIL import ImageFont
7 
8 
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.
13 
14  You can put text to an image including non-ASCII characters.
15 
16  Parameters
17  ==========
18  img : numpy.ndarray
19  cv2 image. bgr order.
20  text : str
21  text information.
22  pos : tuple(float)
23  xy position of text.
24  font_path : str
25  path to font.
26  font_size : int
27  font size
28  color : tuple(int)
29  text color
30  background_color : tuple(int) or None
31  background color in text area. If this value is None, do nothing.
32  offset_x : float
33  x position offset.
34  offset_y : float
35  y position offset.
36  loc : str
37  location.
38  """
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)
45  x, y = pos
46  if loc == 'top':
47  offset_y = (text_h + text_bottom_offset) + offset_y
48  elif loc == 'center':
49  offset_y = offset_y
50  else:
51  raise NotImplementedError('loc {} not implemented.'.format(loc))
52  x0 = x - offset_x
53  y0 = y - offset_y
54  img_h, img_w = img.shape[:2]
55  # check outside of image.
56  if not ((-text_w < x0 < img_w)
57  and (-text_bottom_offset - text_h < y0 < img_h)):
58  return img
59 
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)
63  x0 = int(x0)
64  y0 = int(y0)
65  x1 = int(x1)
66  y1 = int(y1)
67  x2 = int(x2)
68  y2 = int(y2)
69 
70  # Create a black image of the same size as the text area.
71  text_area = np.full(
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)
76  # paste the original image on all or part of it.
77  text_area[y1-y0:y2-y0, x1-x0:x2-x0] = img[y1:y2, x1:x2]
78 
79  # convert pil image to cv2 image.
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)
84 
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]
87  return img
static_virtual_camera.format
format
Definition: static_virtual_camera.py:44
jsk_recognition_utils.put_text.put_text_to_image
def put_text_to_image(img, text, pos, font_path, font_size, color, background_color=None, offset_x=0, offset_y=0, loc='top')
Definition: put_text.py:9


jsk_recognition_utils
Author(s):
autogenerated on Tue Jan 7 2025 04:04:52