SunderAli17 commited on
Commit
d36e4bb
1 Parent(s): 4ffd2b7

Create vis_utils.py

Browse files
Files changed (1) hide show
  1. utils/vis_utils.py +58 -0
utils/vis_utils.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import textwrap
2
+ from typing import List, Tuple, Optional
3
+
4
+ import numpy as np
5
+ from PIL import Image, ImageDraw, ImageFont
6
+
7
+ LINE_WIDTH = 20
8
+
9
+
10
+ def add_text_to_image(image: np.ndarray, text: str, text_color: Tuple[int, int, int] = (0, 0, 0),
11
+ min_lines: Optional[int] = None, add_below: bool = True):
12
+ import textwrap
13
+ lines = textwrap.wrap(text, width=LINE_WIDTH)
14
+ if min_lines is not None and len(lines) < min_lines:
15
+ if add_below:
16
+ lines += [''] * (min_lines - len(lines))
17
+ else:
18
+ lines = [''] * (min_lines - len(lines)) + lines
19
+ h, w, c = image.shape
20
+ offset = int(h * .12)
21
+ img = np.ones((h + offset * len(lines), w, c), dtype=np.uint8) * 255
22
+ font_size = int(offset * .8)
23
+
24
+ try:
25
+ font = ImageFont.truetype("assets/OpenSans-Regular.ttf", font_size)
26
+ textsize = font.getbbox(text)
27
+ y_offset = (offset - textsize[3]) // 2
28
+ except:
29
+ font = ImageFont.load_default()
30
+ y_offset = offset // 2
31
+
32
+ if add_below:
33
+ img[:h] = image
34
+ else:
35
+ img[-h:] = image
36
+ img = Image.fromarray(img)
37
+ draw = ImageDraw.Draw(img)
38
+ for i, line in enumerate(lines):
39
+ line_size = font.getbbox(line)
40
+ text_x = (w - line_size[2]) // 2
41
+ if add_below:
42
+ draw.text((text_x, h + y_offset + offset * i), line, font=font, fill=text_color)
43
+ else:
44
+ draw.text((text_x, 0 + y_offset + offset * i), line, font=font, fill=text_color)
45
+ return np.array(img)
46
+
47
+
48
+ def create_table_plot(titles: List[str], images: List[Image.Image], captions: List[str]) -> Image.Image:
49
+ title_max_lines = np.max([len(textwrap.wrap(text, width=LINE_WIDTH)) for text in titles])
50
+ caption_max_lines = np.max([len(textwrap.wrap(text, width=LINE_WIDTH)) for text in captions])
51
+ out_images = []
52
+ for i in range(len(images)):
53
+ im = np.array(images[i])
54
+ im = add_text_to_image(im, titles[i], add_below=False, min_lines=title_max_lines)
55
+ im = add_text_to_image(im, captions[i], add_below=True, min_lines=caption_max_lines)
56
+ out_images.append(im)
57
+ image = Image.fromarray(np.concatenate(out_images, axis=1))
58
+ return image