-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdecode_visualize.py
56 lines (50 loc) · 2.35 KB
/
decode_visualize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import os
import json
from PIL import Image, ImageDraw, ImageFont
ttf = ImageFont.truetype('misc/Arial.ttf', 9)
def visualize(file, visualization_dir):
image_file = os.path.join(visualization_dir, file + '.jpg')
if not os.path.exists(image_file):
image_file = os.path.join(visualization_dir, file + '.png')
if not os.path.exists(image_file):
image_file = os.path.join(visualization_dir, file + '.tif')
with open(os.path.join(visualization_dir, file + '.json'), 'r', encoding='utf-8') as f:
results = json.load(f)
image = Image.open(image_file).convert('RGB')
width, height = image.size
for bbox, word in results:
draw = ImageDraw.Draw(image)
w1, h1, w2, h2 = bbox
w1 = w1 / 1000 * width
w2 = w2 / 1000 * width
h1 = h1 / 1000 * height
h2 = h2 / 1000 * height
draw.polygon([w1, h1, w2, h1, w2, h2, w1, h2], outline=(255, 0, 0))
try:
draw.text(((w1 + w2) / 2 - len(word) * 2.4, h1 - 3) , word.strip(), fill=(0, 0, 255, 128), font=ttf)
except:
pass
image.save(os.path.join(visualization_dir, file + '-visualization.png'))
def visualize_box(file, visualization_dir):
image_file = os.path.join(visualization_dir, file + '.png')
result_file = os.path.join(visualization_dir, file + '.json')
with open(result_file, 'r', encoding='utf-8') as f:
results = json.load(f)
image = Image.open(image_file).convert('RGB')
width, height = image.size
draw = ImageDraw.Draw(image)
for bbox, word in results:
w1, h1, w2, h2 = bbox
w1 = w1 / 1000 * width
w2 = w2 / 1000 * width
h1 = h1 / 1000 * height
h2 = h2 / 1000 * height
draw.polygon([w1, h1, w2, h1, w2, h2, w1, h2], outline=(255, 0, 0))
image.save(os.path.join(visualization_dir, file + '-visualization-box.png'))
if __name__ == '__main__':
for visualization_dir in filter(lambda x: x.startswith('ViTLP'), os.listdir('decode_output')):
if not os.path.exists(os.path.join('decode_output', visualization_dir)):
os.mkdir(os.path.join('decode_output', visualization_dir))
visualization_dir_ = os.path.join('decode_output', visualization_dir)
for result_file in filter(lambda x: x.endswith('.json'), os.listdir(visualization_dir_)):
visualize(result_file[:-5], visualization_dir_)