daisq commited on
Commit
36e9a77
·
verified ·
1 Parent(s): 7bb6804

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. tools/render_annotated.py +100 -0
  2. tools/util.py +247 -0
tools/render_annotated.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from typing import Tuple, List, Union, Dict, Any
4
+ from util import Visualize
5
+ from PIL import Image, ImageDraw, ImageFont
6
+
7
+ #TODO input your work dir
8
+ BASE_DIR = ""
9
+
10
+ single_img_tasks_no_labels = ["Scene_Classification", "Orientation_Classification", "Environment_State_Classification", "Urban_OCR", "Class_Agnostic_Counting", "Referring_Expression_Counting", "Cross_Object_Reasoning"]
11
+
12
+ single_img_tasks_w_labels = ["Ground_Target_Planning"]
13
+
14
+ multi_img_tasks_no_labels = ["Target_Backtracking", "Intent_Analysis_and_Prediction", "Scene_Attribute_Understanding", "Scene_Damage_Assessment", "Scene_Analysis_and_Prediction", "Temporal_Ordering"]
15
+
16
+ multi_img_tasks_w_labels = ["Air_Ground_Collaborative_Planning", "Swarm_Collaborative_Planning"]
17
+
18
+ video_task = ["Event_Prediction", "Event_Tracing", "Event_Understanding"]
19
+
20
+ def process_multi_img_tasks_w_labels(task_list, BASE_DIR):
21
+ for task in task_list:
22
+ print(f"======Processing {task}======")
23
+ qa = json.load(open(os.path.join(BASE_DIR, "tasks", f"{task}.json"), 'r', encoding='utf-8'))
24
+ for d in qa:
25
+ for item in d["metadata"]["data_resources"]:
26
+ raw_img_p = os.path.join(BASE_DIR, item["path"].replace("annotated", "raw"))
27
+ annotations = []
28
+ for entity in d["target_entities"]:
29
+ if entity["index"] == item["index"]:
30
+ annotations.append(entity)
31
+ vis_img = Visualize(
32
+ image=Image.open(raw_img_p),
33
+ annotations=annotations,
34
+ show_labels=True,
35
+ )
36
+ save_img_p = os.path.join(BASE_DIR, item["path"])
37
+ os.makedirs(os.path.dirname(save_img_p), exist_ok=True)
38
+ vis_img.save(save_img_p, quality=100, subsampling=0)
39
+ print(f"======Processing End {task}======")
40
+
41
+ def process_multi_img_tasks_no_labels(task_list, BASE_DIR):
42
+ for task in task_list:
43
+ print(f"======Processing {task}======")
44
+ qa = json.load(open(os.path.join(BASE_DIR, "tasks", f"{task}.json"), 'r', encoding='utf-8'))
45
+ for d in qa:
46
+ for item in d["metadata"]["data_resources"]:
47
+ raw_img_p = os.path.join(BASE_DIR, item["path"].replace("annotated", "raw"))
48
+ annotations = []
49
+ for entity in d["target_entities"]:
50
+ if entity["index"] == item["index"]:
51
+ annotations.append(entity)
52
+ vis_img = Visualize(
53
+ image=Image.open(raw_img_p),
54
+ annotations=annotations,
55
+ show_labels=False,
56
+ )
57
+ save_img_p = os.path.join(BASE_DIR, item["path"])
58
+ os.makedirs(os.path.dirname(save_img_p), exist_ok=True)
59
+ vis_img.save(save_img_p, quality=100, subsampling=0)
60
+ print(f"======Processing End {task}======")
61
+
62
+ def process_single_img_tasks_no_labels(task_list, BASE_DIR):
63
+ for task in task_list:
64
+ print(f"======Processing {task}======")
65
+ qa = json.load(open(os.path.join(BASE_DIR, "tasks", f"{task}.json"), 'r', encoding='utf-8'))
66
+ for d in qa:
67
+ assert (d["metadata"]["data_type"] == "single_image") and (len(d["metadata"]["data_resources"]) == 1)
68
+ raw_img_p = os.path.join(BASE_DIR, d["metadata"]["data_resources"][0]["path"].replace("annotated", "raw"))
69
+ vis_img = Visualize(
70
+ image=Image.open(raw_img_p),
71
+ annotations=d["target_entities"],
72
+ show_labels=False,
73
+ )
74
+ save_img_p = os.path.join(BASE_DIR, d["metadata"]["data_resources"][0]["path"])
75
+ os.makedirs(os.path.dirname(save_img_p), exist_ok=True)
76
+ vis_img.save(save_img_p, quality=100, subsampling=0)
77
+ print(f"======Processing End {task}======")
78
+
79
+ def process_single_img_tasks_w_labels(task_list, BASE_DIR):
80
+ for task in task_list:
81
+ print(f"======Processing Start {task}======")
82
+ qa = json.load(open(os.path.join(BASE_DIR, "tasks", f"{task}.json"), 'r', encoding='utf-8'))
83
+ for d in qa:
84
+ assert (d["metadata"]["data_type"] == "single_image") and (len(d["metadata"]["data_resources"]) == 1)
85
+ raw_img_p = os.path.join(BASE_DIR, d["metadata"]["data_resources"][0]["path"].replace("annotated", "raw"))
86
+ vis_img = Visualize(
87
+ image=Image.open(raw_img_p),
88
+ annotations=d["target_entities"],
89
+ show_labels=True,
90
+ )
91
+ save_img_p = os.path.join(BASE_DIR, d["metadata"]["data_resources"][0]["path"])
92
+ os.makedirs(os.path.dirname(save_img_p), exist_ok=True)
93
+ vis_img.save(save_img_p, quality=100, subsampling=0)
94
+ print(f"======Processing End {task}======")
95
+
96
+ if __name__ == "__main__":
97
+ process_single_img_tasks_no_labels(single_img_tasks_no_labels, BASE_DIR)
98
+ process_single_img_tasks_w_labels(single_img_tasks_w_labels, BASE_DIR)
99
+ process_multi_img_tasks_no_labels(multi_img_tasks_no_labels, BASE_DIR)
100
+ process_multi_img_tasks_w_labels(multi_img_tasks_w_labels, BASE_DIR)
tools/util.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Modified from: https://github.com/IDEA-Research/Rex-Omni/blob/master/rex_omni/utils.py
3
+ """
4
+ from typing import Any, Dict, List, Optional, Tuple
5
+
6
+ import numpy as np
7
+ from PIL import Image, ImageDraw, ImageFont
8
+
9
+ class ColorGenerator:
10
+ """Generate consistent colors for visualization"""
11
+
12
+ def __init__(self, color_type: str = "text"):
13
+ self.color_type = color_type
14
+
15
+ if color_type == "same":
16
+ self.color = tuple((np.random.randint(0, 127, size=3) + 128).tolist())
17
+ elif color_type == "text":
18
+ np.random.seed(3396)
19
+ self.num_colors = 300
20
+ self.colors = np.random.randint(0, 127, size=(self.num_colors, 3)) + 128
21
+ else:
22
+ raise ValueError(f"Unknown color type: {color_type}")
23
+
24
+ def get_color(self, text: str) -> Tuple[int, int, int]:
25
+ """Get color for given text"""
26
+ if self.color_type == "same":
27
+ return self.color
28
+
29
+ if self.color_type == "text":
30
+ text_hash = hash(text)
31
+ index = text_hash % self.num_colors
32
+ color = tuple(self.colors[index])
33
+ return color
34
+
35
+ raise ValueError(f"Unknown color type: {self.color_type}")
36
+
37
+ def Visualize(
38
+ image: Image.Image,
39
+ annotations: Dict[str, List[Dict]],
40
+ font_size: int = 10,
41
+ draw_width: int = 6,
42
+ show_labels: bool = True,
43
+ custom_colors: Optional[Dict[str, Tuple[int, int, int]]] = None,
44
+ font_path: Optional[str] = None,
45
+ ) -> Image.Image:
46
+ """
47
+ Visualize predictions on image
48
+
49
+ Args:
50
+ image: Input image
51
+ annotations: Target entities (from the JSON file) need to be drawn on the image
52
+ font_size: Font size for labels
53
+ draw_width: Line width for drawing
54
+ show_labels: Whether to show text labels
55
+ custom_colors: Custom colors for categories
56
+ font_path: Path to font file
57
+
58
+ Returns:
59
+ Image with visualizations
60
+ """
61
+
62
+ # Create a copy of the image
63
+ vis_image = image.copy()
64
+ draw = ImageDraw.Draw(vis_image)
65
+
66
+ # Load font
67
+ font = _load_font(font_size, font_path)
68
+
69
+ # Color generator
70
+ color_generator = ColorGenerator("same")
71
+ color_generator.color = (255, 0, 0)
72
+
73
+ for i, entity in enumerate(annotations):
74
+ # Get color
75
+ color = color_generator.color
76
+ annotation_type = entity.get("entity_type", "region")
77
+ coords = entity.get("bbox", [])
78
+
79
+ if annotation_type in ["region", "object", "human"] and len(coords) == 4:
80
+ draw_width = _adjust_draw_width(coords, vis_image.size)
81
+ if "label" in entity.keys():
82
+ _draw_box(draw, coords, color, draw_width, entity["label"], font, show_labels)
83
+ else:
84
+ _draw_box(draw, coords, color, draw_width, "", font, show_labels=False)
85
+ elif annotation_type == "point" and len(coords) == 2:
86
+ draw_width = 1
87
+ _draw_point(
88
+ draw, coords, color, draw_width, entity["label"], font, show_labels
89
+ )
90
+
91
+ return vis_image
92
+
93
+ def _adjust_draw_width(
94
+ coords: List[float],
95
+ image_size: Tuple[int, int]
96
+ ) -> int:
97
+ x0, y0, x1, y1 = coords
98
+ image_width, image_height = image_size
99
+
100
+ box_width = max(1, x1 - x0)
101
+ box_height = max(1, y1 - y0)
102
+ box_area = box_width * box_height
103
+ image_total_area = image_width * image_height
104
+
105
+ if image_total_area == 0:
106
+ return 6
107
+
108
+ area_ratio = box_area / image_total_area
109
+
110
+ if area_ratio >= 0.05:
111
+ return 6
112
+ elif area_ratio >= 0.01:
113
+ return 4
114
+ elif area_ratio >= 0.005:
115
+ return 3
116
+ else:
117
+ return 2
118
+
119
+ def _load_font(font_size: int, font_path: Optional[str] = None) -> ImageFont.ImageFont:
120
+ """Load font for drawing"""
121
+ font_paths = [
122
+ "C:/Windows/Fonts/simhei.ttf",
123
+ "C:/Windows/Fonts/arial.ttf",
124
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
125
+ "/System/Library/Fonts/Arial.ttf",
126
+ "/System/Library/Fonts/Helvetica.ttc",
127
+ "arial.ttf",
128
+ ]
129
+
130
+ font = None
131
+ for font_path_ in font_paths:
132
+ try:
133
+ font = ImageFont.truetype(font_path_, font_size)
134
+ break
135
+ except:
136
+ continue
137
+
138
+ if font is None:
139
+ font = ImageFont.load_default()
140
+
141
+ return font
142
+
143
+ def _draw_box(
144
+ draw: ImageDraw.ImageDraw,
145
+ coords: List[float],
146
+ color: Tuple[int, int, int],
147
+ draw_width: int,
148
+ label: str,
149
+ font: ImageFont.ImageFont,
150
+ show_labels: bool,
151
+ ):
152
+ """Draw bounding box"""
153
+ x0, y0, x1, y1 = [int(c) for c in coords]
154
+
155
+ # Check valid box
156
+ if x0 >= x1 or y0 >= y1:
157
+ return
158
+
159
+ # Draw rectangle
160
+ draw.rectangle([x0, y0, x1, y1], outline=color, width=draw_width)
161
+
162
+ # Draw label
163
+ if show_labels and label:
164
+ bbox = draw.textbbox((x0, y0), label, font)
165
+ box_h = bbox[3] - bbox[1]
166
+
167
+ y0_text = y0 - box_h - (draw_width * 2)
168
+ y1_text = y0 + draw_width
169
+
170
+ if y0_text < 0:
171
+ y0_text = 0
172
+ y1_text = y0 + 2 * draw_width + box_h
173
+
174
+ draw.rectangle(
175
+ [x0, y0_text, bbox[2] + draw_width * 2, y1_text],
176
+ fill=color,
177
+ )
178
+ draw.text(
179
+ (x0 + draw_width, y0_text),
180
+ label,
181
+ fill="black",
182
+ font=font,
183
+ )
184
+
185
+
186
+ def _draw_point(
187
+ draw: ImageDraw.ImageDraw,
188
+ coords: List[float],
189
+ color: Tuple[int, int, int],
190
+ draw_width: int,
191
+ label: str,
192
+ font: ImageFont.ImageFont,
193
+ show_labels: bool,
194
+ ):
195
+ """Draw point"""
196
+ x, y = [int(c) for c in coords]
197
+
198
+ # Draw point as circle
199
+ radius = min(8, draw_width)
200
+ border_width = 2
201
+
202
+ # Draw white border
203
+ draw.ellipse(
204
+ [
205
+ x - radius - border_width,
206
+ y - radius - border_width,
207
+ x + radius + border_width,
208
+ y + radius + border_width,
209
+ ],
210
+ fill="white",
211
+ outline="white",
212
+ )
213
+
214
+ # Draw colored center
215
+ draw.ellipse(
216
+ [x - radius, y - radius, x + radius, y + radius],
217
+ fill=color,
218
+ outline=color,
219
+ )
220
+
221
+ # Draw label
222
+ if show_labels and label:
223
+ label_x, label_y = x + 5, y - 5
224
+ if label_y < 0:
225
+ label_y = y + 15
226
+ bbox = draw.textbbox((label_x, label_y), label, font)
227
+ box_h = bbox[3] - bbox[1]
228
+ box_w = bbox[2] - bbox[0]
229
+
230
+ padding = 4
231
+
232
+ """
233
+ We choose not to draw background as the ground occludes key perceptual information in many cases.
234
+ """
235
+ # Draw background
236
+ # draw.rectangle(
237
+ # [
238
+ # label_x - padding,
239
+ # label_y - box_h - padding,
240
+ # label_x + box_w + padding,
241
+ # label_y + padding,
242
+ # ],
243
+ # fill=color,
244
+ # )
245
+
246
+ # Draw text
247
+ draw.text((label_x, label_y - box_h), label, fill="red", font=font)