weihongliang commited on
Commit
e6edcfa
·
verified ·
1 Parent(s): 406fd9e

Upload 5 files

Browse files
utils/__pycache__/data_utils.cpython-310.pyc ADDED
Binary file (5.99 kB). View file
 
utils/__pycache__/visualizer.cpython-310.pyc ADDED
Binary file (42.5 kB). View file
 
utils/data_utils.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ These functions are work on a set of images in a directory.
6
+ """
7
+ import cv2
8
+ import copy
9
+ import glob
10
+ import os
11
+ import re
12
+ import sys
13
+ import numpy as np
14
+ from PIL import Image
15
+ from subprocess import check_output
16
+
17
+
18
+ def minify(datadir, destdir, factors=[], resolutions=[], extend='png'):
19
+ """Using mogrify to resize rgb image
20
+
21
+ Args:
22
+ datadir(str): source data path
23
+ destdir(str): save path
24
+ factor(int): ratio of original width or height
25
+ resolutions(int): new width or height
26
+ """
27
+ imgs = [os.path.join(datadir, f) for f in sorted(os.listdir(datadir))]
28
+ imgs = [f for f in imgs if any([f.endswith(ex) for ex in ['JPG', 'jpg', 'png', 'jpeg', 'PNG']])]
29
+
30
+ wd = os.getcwd()
31
+
32
+ for r in factors + resolutions:
33
+ if isinstance(r, int):
34
+ name = 'images_{}'.format(r)
35
+ resizearg = '{}%'.format(int(r))
36
+ else:
37
+ name = 'images_{}x{}'.format(r[1], r[0])
38
+ resizearg = '{}x{}'.format(r[1], r[0])
39
+ if os.path.exists(destdir):
40
+ continue
41
+
42
+ print('Minifying', r, datadir)
43
+
44
+ os.makedirs(destdir)
45
+ check_output('cp {}/* {}'.format(datadir, destdir), shell=True)
46
+
47
+ ext = imgs[0].split('.')[-1]
48
+ args = ' '.join(['mogrify', '-resize', resizearg, '-format', extend, '*.{}'.format(ext)])
49
+
50
+ print(args)
51
+ os.chdir(destdir)
52
+ check_output(args, shell=True)
53
+ os.chdir(wd)
54
+
55
+ if ext != extend:
56
+ check_output('rm {}/*.{}'.format(destdir, ext), shell=True)
57
+ print('Removed duplicates')
58
+ print('Done')
59
+
60
+
61
+ def resizemask(datadir, destdir, factors=[], resolutions=[]):
62
+ """Using PIL.Image.resize to resize binary images with nearest-neighbor
63
+
64
+ Args:
65
+ datadir(str): source data path
66
+ destdir(str): save path
67
+ factor(float): 1/N original width or height
68
+ resolutions(int): new width or height
69
+ """
70
+ mask_paths = sorted([p for p in glob.glob(os.path.join(datadir, '*'))
71
+ if re.search('/*\.(jpg|jpeg|png|gif|bmp)', str(p))])
72
+ old_size = np.array(Image.open(mask_paths[0])).shape
73
+ if len(old_size) != 2:
74
+ old_size = old_size[:2]
75
+
76
+ for r in factors + resolutions:
77
+ if isinstance(r, int):
78
+ width = int(old_size[0] / r)
79
+ height = int(old_size[1] / r)
80
+ else:
81
+ width = r[0]
82
+ height = r[1]
83
+ if os.path.exists(destdir):
84
+ continue
85
+ else:
86
+ os.makedirs(destdir)
87
+
88
+ for i, mask_path in enumerate(mask_paths):
89
+ mask = Image.open(mask_path)
90
+ new_mask = mask.resize((width, height))
91
+
92
+ base_filename = mask_path.split('/')[-1]
93
+ new_mask.save(os.path.join(destdir, base_filename))
94
+
95
+ print('Done')
96
+
97
+
98
+ def getbbox(mask, exponent=1):
99
+ """Computing bboxes of foreground in the masks
100
+
101
+ Args:
102
+ mask: binary image
103
+ exponent(int): the size (width or height) should be a multiple of exponent
104
+ """
105
+
106
+ x_center = mask.shape[0] // 2
107
+ y_center = mask.shape[1] // 2
108
+
109
+ x, y = (mask != 0).nonzero() # x:height; y:width
110
+ bbox = [min(x), max(x), min(y), max(y)]
111
+
112
+ # nearest rectangle box that height/width is the multipler of a factor
113
+ x_min = np.max([bbox[1] - x_center, x_center - bbox[0]]) * 2
114
+ y_min = np.max([bbox[3] - y_center, y_center - bbox[2]]) * 2
115
+ new_x = int(np.ceil(x_min / exponent) * exponent)
116
+ new_y = int(np.ceil(y_min / exponent) * exponent)
117
+ # print("A rectangle to bound the object with width and height:", (new_y, new_x))
118
+
119
+ bbox = [x_center - new_x // 2, x_center + new_x // 2,
120
+ y_center - new_y // 2, y_center + new_y // 2]
121
+ return bbox
122
+
123
+
124
+ def centercrop(img, new_size):
125
+ """Computing bboxes of foreground in the masks
126
+
127
+ Args:
128
+ img: PIL image
129
+ exponent(int): the size (width or height) should be a multiple of exponent
130
+ """
131
+ if len(new_size) == 2:
132
+ new_width = new_size[0]
133
+ new_height = new_size[1]
134
+ else:
135
+ print('ERROR: Valid size not found. Aborting')
136
+ sys.exit()
137
+
138
+ width, height = img.size
139
+ left = (width - new_width) // 2
140
+ top = (height - new_height) // 2
141
+ right = (width + new_width) // 2
142
+ bottom = (height + new_height) // 2
143
+
144
+ new_img = img.crop((left, top, right, bottom))
145
+
146
+ return new_img
147
+
148
+
149
+ def invertmask(img, mask):
150
+ # mask only has 0 and 1, extract the foreground
151
+ fg = cv2.bitwise_and(img, img, mask=mask)
152
+
153
+ # create white background
154
+ black_bg = np.zeros(img.shape, np.uint8)
155
+ white_bg = ~black_bg
156
+
157
+ # masking the white background
158
+ white_bg = cv2.bitwise_and(white_bg, white_bg, mask=mask)
159
+ white_bg = ~white_bg
160
+
161
+ # foreground will be added to the black area
162
+ new_img = cv2.add(white_bg, img)
163
+
164
+ # invert mask to 0 for foreground and 255 for background
165
+ new_mask = np.where(mask == 0, 255, 0)
166
+
167
+ return new_img, new_mask
168
+
169
+ def gen_square_crops(img, bbox, padding_color=(255, 255, 255), upscale_quality=Image.LANCZOS):
170
+ """
171
+ Generate square crops from an image based on a bounding box.
172
+
173
+ Args:
174
+ img: PIL Image object
175
+ bbox: Tuple of (x0, y0, x1, y1) coordinates
176
+ padding_color: Color for padding (default white)
177
+ upscale_quality: Resampling method for upscaling (default LANCZOS)
178
+
179
+ Returns:
180
+ PIL Image object with square crop
181
+ """
182
+ img_width, img_height = img.size
183
+ x0, y0, x1, y1 = bbox
184
+
185
+ # Calculate original width and height of the bbox
186
+ bbox_width = x1 - x0
187
+ bbox_height = y1 - y0
188
+
189
+ # Determine the size of the square crop
190
+ new_size = max(bbox_width, bbox_height)
191
+
192
+ # Calculate center of the original bbox
193
+ center_x = x0 + bbox_width // 2
194
+ center_y = y0 + bbox_height // 2
195
+
196
+ # Calculate new coordinates that maintain the square aspect ratio
197
+ half_size = new_size // 2
198
+
199
+ # Adjust coordinates to stay within image boundaries
200
+ new_x0 = max(0, center_x - half_size)
201
+ new_y0 = max(0, center_y - half_size)
202
+ new_x1 = min(img_width, center_x + half_size)
203
+ new_y1 = min(img_height, center_y + half_size)
204
+
205
+ # If we're at the edges, adjust the other side to maintain square size
206
+ if new_x0 == 0 and new_x1 < img_width:
207
+ new_x1 = min(img_width, new_x0 + new_size)
208
+ elif new_x1 == img_width and new_x0 > 0:
209
+ new_x0 = max(0, new_x1 - new_size)
210
+
211
+ if new_y0 == 0 and new_y1 < img_height:
212
+ new_y1 = min(img_height, new_y0 + new_size)
213
+ elif new_y1 == img_height and new_y0 > 0:
214
+ new_y0 = max(0, new_y1 - new_size)
215
+
216
+ # Crop the image
217
+ cropped_img = img.crop((new_x0, new_y0, new_x1, new_y1))
218
+
219
+ # Create a new square image
220
+ square_img = Image.new('RGB', (new_size, new_size), padding_color)
221
+
222
+ # Calculate paste position (centered)
223
+ paste_x = (new_size - (new_x1 - new_x0)) // 2
224
+ paste_y = (new_size - (new_y1 - new_y0)) // 2
225
+
226
+ # Paste the cropped image onto the square canvas
227
+ square_img.paste(cropped_img, (paste_x, paste_y))
228
+
229
+ # If the original crop was smaller than new_size, we need to resize with anti-aliasing
230
+ if (new_x1 - new_x0) < new_size or (new_y1 - new_y0) < new_size:
231
+ # Calculate the scale factor
232
+ scale = new_size / max(bbox_width, bbox_height)
233
+
234
+ # Resize the original crop with anti-aliasing
235
+ resized_crop = img.crop((x0, y0, x1, y1)).resize(
236
+ (int(bbox_width * scale), int(bbox_height * scale)),
237
+ resample=upscale_quality
238
+ )
239
+
240
+ # Create new square image
241
+ square_img = Image.new('RGB', (new_size, new_size), padding_color)
242
+
243
+ # Calculate centered position
244
+ paste_x = (new_size - resized_crop.width) // 2
245
+ paste_y = (new_size - resized_crop.height) // 2
246
+
247
+ # Paste the resized image
248
+ square_img.paste(resized_crop, (paste_x, paste_y))
249
+
250
+ return square_img
utils/pascal2coco.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ parse pascal_voc XML file to COCO json
6
+ """
7
+ import torch
8
+ import glob
9
+ import os
10
+ import random
11
+ import re
12
+ import shutil
13
+ import json
14
+ import xml.etree.ElementTree as ET
15
+ from sklearn.model_selection import train_test_split
16
+ from data_utils import minify
17
+
18
+ CATEGORIES = ["000_aveda_shampoo", "001_binder_clips_median", "002_binder_clips_small", "003_bombik_bucket",
19
+ "004_bonne_maman_blueberry", "005_bonne_maman_raspberry", "006_bonne_maman_strawberry",
20
+ "007_costa_caramel", "008_essential_oil_bergamot", "009_garlic_toast_spread", "010_handcream_avocado",
21
+ "011_hb_calcium", "012_hb_grapeseed", "013_hb_marine_collagen", "014_hellmanns_mayonnaise",
22
+ "015_illy_blend", "016_japanese_finger_cookies", "017_john_west_canned_tuna", "018_kerastase_shampoo",
23
+ "019_kiehls_facial_cream", "020_kiihne_balsamic", "021_kiihne_honey_mustard", "022_lindor_matcha",
24
+ "023_lindor_salted_caramel", "024_lush_mask", "025_pasta_sauce_black_pepper", "026_pasta_sauce_tomato",
25
+ "027_pepsi", "028_portable_yogurt_machine", "029_selfile_stick", "030_sour_lemon_drops",
26
+ "031_sticky_notes", "032_stridex_green", "033_thermos_flask_cream", "034_thermos_flask_muji",
27
+ "035_thermos_flask_sliver", "036_tragata_olive_oil", "037_tulip_luncheon_meat", "038_unicharm_cotton_pad",
28
+ "039_vinda_tissue", "040_wrigley_doublemint_gum", "041_baseball_cap_black", "042_baseball_cap_pink",
29
+ "043_bfe_facial_mask", "044_corgi_doll", "045_dinosaur_doll", "046_geo_mocha", "047_geo_roast_charcoal",
30
+ "048_instant_noodle_black", "049_instant_noodle_red", "050_nabati_cheese_wafer", "051_truffettes",
31
+ "052_acnes_cream", "053_aveda_conditioner", "054_banana_milk_drink", "055_candle_beast",
32
+ "056_china_persimmon", "057_danisa_butter_cookies", "058_effaclar_duo", "059_evelom_cleanser",
33
+ "060_glasses_box_blone", "061_handcream_iris", "062_handcream_lavender", "063_handcream_rosewater",
34
+ "064_handcream_summer_hill", "065_hr_serum", "066_japanese_chocolate", "067_kerastase_hair_treatment",
35
+ "068_kiehls_serum", "069_korean_beef_marinade", "070_korean_doenjang", "071_korean_gochujang",
36
+ "072_korean_ssamjang", "073_loccitane_soap", "074_marvis_toothpaste_purple", "075_mouse_thinkpad",
37
+ "076_oatly_chocolate", "077_oatly_original", "078_ousa_grated_cheese", "079_polaroid_film",
38
+ "080_skinceuticals_be", "081_skinceuticals_cf", "082_skinceuticals_phyto", "083_stapler_black",
39
+ "084_stapler_blue", "085_sunscreen_blue", "086_tempo_pocket_tissue", "087_thermos_flask_purple",
40
+ "088_uha_matcha", "089_urban_decay_spray", "090_vitaboost_multivitamin", "091_watercolor_penbox",
41
+ "092_youthlt_bilberry_complex", "093_daiso_mod_remover", "094_kaneyo_kitchen_bleach",
42
+ "095_lays_chip_bag_blue", "096_lays_chip_bag_green", "097_lays_chip_tube_auburn",
43
+ "098_lays_chip_tube_green", "099_mug_blue"]
44
+
45
+
46
+ def readXML(xml_file):
47
+ data = []
48
+ tree = ET.parse(xml_file)
49
+ root = tree.getroot()
50
+ info = {}
51
+ info['dataname'] = []
52
+ info['filename'] = []
53
+ info['width'] = 1024
54
+ info['height'] = 768
55
+ info['depth'] = 1
56
+
57
+ for eles in root:
58
+ if eles.tag == 'folder':
59
+ info['dataname'] = eles.text
60
+ elif eles.tag == 'filename':
61
+ info['filename'] = eles.text
62
+ elif eles.tag == 'size':
63
+ for elem in eles:
64
+ if elem.tag == 'width':
65
+ info['width'] = elem.text
66
+ elif elem.tag == 'height':
67
+ info['height'] = elem.text
68
+ elif elem.tag == 'depth':
69
+ info['depth'] = elem.text
70
+ else:
71
+ continue
72
+ elif eles.tag == 'object':
73
+ anno = dict()
74
+ for elem in eles:
75
+ if elem.tag == 'name':
76
+ anno['name'] = elem.text
77
+ elif elem.tag == 'bndbox':
78
+ for subelem in elem:
79
+ if subelem.tag == 'xmin':
80
+ anno['xmin'] = float(subelem.text)
81
+ elif subelem.tag == 'xmax':
82
+ anno['xmax'] = float(subelem.text)
83
+ elif subelem.tag == 'ymin':
84
+ anno['ymin'] = float(subelem.text)
85
+ elif subelem.tag == 'ymax':
86
+ anno['ymax'] = float(subelem.text)
87
+ else:
88
+ continue
89
+ data.append(anno)
90
+
91
+ return info, data
92
+
93
+
94
+ def getCOCOjson(root_path, save_path, factor=1.0, flag=None):
95
+ # parse all .xml files to a .json file
96
+ dataset = dict()
97
+ dataset['info'] = {}
98
+ dataset['licenses'] = []
99
+ dataset['images'] = []
100
+ dataset['annotations'] = []
101
+ dataset['categories'] = []
102
+
103
+ dataset['info']['description'] = 'RealWorld Dataset'
104
+ dataset['info']['url'] = ''
105
+ dataset['info']['version'] = '1.0'
106
+ dataset['info']['year'] = 2023
107
+ dataset['info']['contributor'] = ''
108
+ dataset['info']['date_created'] = ''
109
+
110
+ licenses = {}
111
+ licenses['url'] = ''
112
+ licenses['id'] = 1
113
+ licenses['name'] = ''
114
+ dataset['licenses'].append(licenses)
115
+
116
+ all_anno_count = 0
117
+ img_list = sorted([p for p in glob.glob(os.path.join(root_path, 'images', '*'))
118
+ if re.search('/*\.(jpg|jpeg|png|gif|bmp)', str(p))])
119
+ for i_img, img_file in enumerate(img_list):
120
+ file_name = os.path.basename(img_file)
121
+ if flag == 'test':
122
+ anno_path = os.path.join(root_path, 'annotations',
123
+ file_name.split('.')[0] + '.xml') # .xml files for RealScenes
124
+ else:
125
+ anno_path = os.path.join(root_path, 'annotations',
126
+ file_name.split('_')[0] + '.xml') # .xml files for cut-paste-learn
127
+
128
+ info, objects = readXML(anno_path)
129
+
130
+ # images
131
+ images = {}
132
+ images['license'] = 1
133
+ images['file_name'] = file_name
134
+ images['coco_url'] = ''
135
+ images['height'] = int(float(info['height']) * factor)
136
+ images['width'] = int(float(info['width']) * factor)
137
+ images['date_captured'] = ''
138
+ images['flickr_url'] = ''
139
+ images['id'] = int(i_img)
140
+
141
+ dataset['images'].append(images)
142
+
143
+ # annotations
144
+ for object in objects:
145
+ if int(object['name'].split('_')[0]) > len(CATEGORIES) - 1:
146
+ continue
147
+ # bbox: [xmin,ymin,w,h]
148
+ bbox = []
149
+ bbox.append(object['xmin'])
150
+ bbox.append(object['ymin'])
151
+ bbox.append(object['xmax'] - object['xmin'])
152
+ bbox.append(object['ymax'] - object['ymin'])
153
+
154
+ if factor != 1:
155
+ bbox = [x * factor for x in bbox]
156
+
157
+ # when segmentation annotation not given, use [[x1,y1,x2,y1,x2,y2,x1,y2]] instead
158
+ segmentation = [[bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1],
159
+ bbox[0] + bbox[2], bbox[1] + bbox[3], bbox[0], bbox[1] + bbox[3]]]
160
+
161
+ annotations = {}
162
+ annotations['segmentation'] = segmentation
163
+ annotations['area'] = bbox[-1] * bbox[-2]
164
+ annotations['iscrowd'] = 0
165
+ annotations['image_id'] = int(i_img)
166
+ annotations['bbox'] = bbox
167
+ annotations['category_id'] = int(object['name'].split('_')[0])
168
+ annotations['id'] = all_anno_count
169
+
170
+ dataset['annotations'].append(annotations)
171
+ all_anno_count += 1
172
+
173
+ # categories
174
+ for i_cat, cat in enumerate(CATEGORIES):
175
+ categories = {}
176
+ categories['supercategory'] = cat
177
+ categories['id'] = i_cat
178
+ categories['name'] = cat
179
+ dataset['categories'].append(categories)
180
+
181
+ with open(save_path, 'w', encoding='utf-8') as f:
182
+ json.dump(dataset, f)
183
+ print('ok')
184
+
185
+
186
+ if __name__ == '__main__':
187
+
188
+ # root_path = "../syndata-generation/syndata_1"
189
+
190
+ # image_paths = os.listdir(os.path.join(root_path, 'images'))
191
+ # # train:val = 0.75:0.25
192
+ # image_train, image_val = train_test_split(image_paths, test_size=0.25, random_state=77)
193
+
194
+ # # copy image to train set --> create train_json
195
+ # if not os.path.exists(os.path.join(root_path, 'train')):
196
+ # os.makedirs(os.path.join(root_path, 'train', 'images'))
197
+ # os.makedirs(os.path.join(root_path, 'train/annotations'))
198
+
199
+ # for name in image_train:
200
+ # shutil.copy(os.path.join(root_path, 'images', name),
201
+ # os.path.join(root_path, 'train/images', name))
202
+ # shutil.copy(os.path.join(root_path, 'annotations', name.split('_')[0] + '.xml'),
203
+ # os.path.join(root_path, 'train/annotations', name.split('_')[0] + '.xml'))
204
+
205
+ # getCOCOjson(os.path.join(root_path, 'train'), os.path.join(root_path, 'instances_train.json'))
206
+
207
+ # # copy image to val set --> create val_json
208
+ # if not os.path.exists(os.path.join(root_path, 'val')):
209
+ # os.makedirs(os.path.join(root_path, 'val/images'))
210
+ # os.makedirs(os.path.join(root_path, 'val/annotations'))
211
+
212
+ # for name in image_val:
213
+ # shutil.copy(os.path.join(root_path, 'images', name),
214
+ # os.path.join(root_path, 'val/images', name))
215
+ # shutil.copy(os.path.join(root_path, 'annotations', name.split('_')[0] + '.xml'),
216
+ # os.path.join(root_path, 'val/annotations', name.split('_')[0] + '.xml'))
217
+
218
+ # getCOCOjson(os.path.join(root_path, 'val'), os.path.join(root_path, 'instances_val.json'))
219
+
220
+ # test data
221
+
222
+ level = 'hard' # 'all', 'hard', 'easy'
223
+ factor = 1
224
+ root_path = "../InsDet/Scenes"
225
+ test_path = "../database/Data/test_" + str(factor) + '_' + str(level)
226
+ if not os.path.exists(os.path.join(test_path, 'images')):
227
+ os.makedirs(os.path.join(test_path, 'images'))
228
+ if not os.path.exists(os.path.join(test_path, 'annotations')):
229
+ os.makedirs(os.path.join(test_path, 'annotations'))
230
+
231
+ if level == 'all':
232
+ image_paths = sorted([p for p in glob.glob(os.path.join(root_path, '*/*/*'))
233
+ if re.search('/*\.(jpg|jpeg|png|gif|bmp)', str(p))])
234
+ anno_paths = sorted([p for p in glob.glob(os.path.join(root_path, '*/*/*'))
235
+ if re.search('/*\.xml', str(p))])
236
+ else:
237
+ image_paths = sorted([p for p in glob.glob(os.path.join(root_path, level, '*/*'))
238
+ if re.search('/*\.(jpg|jpeg|png|gif|bmp)', str(p))])
239
+ anno_paths = sorted([p for p in glob.glob(os.path.join(root_path, level, '*/*'))
240
+ if re.search('/*\.xml', str(p))])
241
+
242
+ for i, file_path in enumerate(zip(image_paths, anno_paths)):
243
+ file_name = 'test_' + '%03d' % i
244
+ img_extend = os.path.splitext(file_path[0])[-1] # extend for image file
245
+ anno_extend = os.path.splitext(file_path[1])[-1] # extend for image file
246
+
247
+ shutil.copyfile(file_path[0], os.path.join(test_path, 'images', file_name + img_extend))
248
+ shutil.copyfile(file_path[1], os.path.join(test_path, 'annotations', file_name + anno_extend))
249
+
250
+ getCOCOjson(os.path.join(test_path),
251
+ os.path.join(test_path, "instances_test_" + str(factor) + '_' + str(level) + ".json"),
252
+ factor=1/factor, flag='test')
253
+ # height = 6144
254
+ # width = 8192
255
+ # minify(os.path.join(test_path, 'images'), os.path.join(test_path, 'test'),
256
+ # factors=[], resolutions=[[int(height / factor), int(width / factor)]], extend='jpg')
257
+
258
+
utils/visualizer.py ADDED
@@ -0,0 +1,1283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ import colorsys
3
+ import logging
4
+ import math
5
+ import numpy as np
6
+ from enum import Enum, unique
7
+ import cv2
8
+ import matplotlib as mpl
9
+ import matplotlib.colors as mplc
10
+ import matplotlib.figure as mplfigure
11
+ import pycocotools.mask as mask_util
12
+ import torch
13
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
14
+ from PIL import Image
15
+
16
+ from detectron2.data import MetadataCatalog
17
+ from detectron2.structures import BitMasks, Boxes, BoxMode, Keypoints, PolygonMasks, RotatedBoxes
18
+ from detectron2.utils.file_io import PathManager
19
+
20
+ from detectron2.utils.colormap import random_color
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ __all__ = ["ColorMode", "VisImage", "Visualizer"]
25
+
26
+ _SMALL_OBJECT_AREA_THRESH = 1000
27
+ _LARGE_MASK_AREA_THRESH = 120000
28
+ _OFF_WHITE = (1.0, 1.0, 240.0 / 255)
29
+ _BLACK = (0, 0, 0)
30
+ _RED = (1.0, 0, 0)
31
+
32
+ _KEYPOINT_THRESHOLD = 0.05
33
+
34
+
35
+ @unique
36
+ class ColorMode(Enum):
37
+ """
38
+ Enum of different color modes to use for instance visualizations.
39
+ """
40
+
41
+ IMAGE = 0
42
+ """
43
+ Picks a random color for every instance and overlay segmentations with low opacity.
44
+ """
45
+ SEGMENTATION = 1
46
+ """
47
+ Let instances of the same category have similar colors
48
+ (from metadata.thing_colors), and overlay them with
49
+ high opacity. This provides more attention on the quality of segmentation.
50
+ """
51
+ IMAGE_BW = 2
52
+ """
53
+ Same as IMAGE, but convert all areas without masks to gray-scale.
54
+ Only available for drawing per-instance mask predictions.
55
+ """
56
+
57
+
58
+ class GenericMask:
59
+ """
60
+ Attribute:
61
+ polygons (list[ndarray]): list[ndarray]: polygons for this mask.
62
+ Each ndarray has format [x, y, x, y, ...]
63
+ mask (ndarray): a binary mask
64
+ """
65
+
66
+ def __init__(self, mask_or_polygons, height, width):
67
+ self._mask = self._polygons = self._has_holes = None
68
+ self.height = height
69
+ self.width = width
70
+
71
+ m = mask_or_polygons
72
+ if isinstance(m, dict):
73
+ # RLEs
74
+ assert "counts" in m and "size" in m
75
+ if isinstance(m["counts"], list): # uncompressed RLEs
76
+ h, w = m["size"]
77
+ assert h == height and w == width
78
+ m = mask_util.frPyObjects(m, h, w)
79
+ self._mask = mask_util.decode(m)[:, :]
80
+ return
81
+
82
+ if isinstance(m, list): # list[ndarray]
83
+ self._polygons = [np.asarray(x).reshape(-1) for x in m]
84
+ return
85
+
86
+ if isinstance(m, np.ndarray): # assumed to be a binary mask
87
+ assert m.shape[1] != 2, m.shape
88
+ assert m.shape == (
89
+ height,
90
+ width,
91
+ ), f"mask shape: {m.shape}, target dims: {height}, {width}"
92
+ self._mask = m.astype("uint8")
93
+ return
94
+
95
+ raise ValueError("GenericMask cannot handle object {} of type '{}'".format(m, type(m)))
96
+
97
+ @property
98
+ def mask(self):
99
+ if self._mask is None:
100
+ self._mask = self.polygons_to_mask(self._polygons)
101
+ return self._mask
102
+
103
+ @property
104
+ def polygons(self):
105
+ if self._polygons is None:
106
+ self._polygons, self._has_holes = self.mask_to_polygons(self._mask)
107
+ return self._polygons
108
+
109
+ @property
110
+ def has_holes(self):
111
+ if self._has_holes is None:
112
+ if self._mask is not None:
113
+ self._polygons, self._has_holes = self.mask_to_polygons(self._mask)
114
+ else:
115
+ self._has_holes = False # if original format is polygon, does not have holes
116
+ return self._has_holes
117
+
118
+ def mask_to_polygons(self, mask):
119
+ # cv2.RETR_CCOMP flag retrieves all the contours and arranges them to a 2-level
120
+ # hierarchy. External contours (boundary) of the object are placed in hierarchy-1.
121
+ # Internal contours (holes) are placed in hierarchy-2.
122
+ # cv2.CHAIN_APPROX_NONE flag gets vertices of polygons from contours.
123
+ mask = np.ascontiguousarray(mask) # some versions of cv2 does not support incontiguous arr
124
+ res = cv2.findContours(mask.astype("uint8"), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
125
+ hierarchy = res[-1]
126
+ if hierarchy is None: # empty mask
127
+ return [], False
128
+ has_holes = (hierarchy.reshape(-1, 4)[:, 3] >= 0).sum() > 0
129
+ res = res[-2]
130
+ res = [x.flatten() for x in res]
131
+ # These coordinates from OpenCV are integers in range [0, W-1 or H-1].
132
+ # We add 0.5 to turn them into real-value coordinate space. A better solution
133
+ # would be to first +0.5 and then dilate the returned polygon by 0.5.
134
+ res = [x + 0.5 for x in res if len(x) >= 6]
135
+ return res, has_holes
136
+
137
+ def polygons_to_mask(self, polygons):
138
+ rle = mask_util.frPyObjects(polygons, self.height, self.width)
139
+ rle = mask_util.merge(rle)
140
+ return mask_util.decode(rle)[:, :]
141
+
142
+ def area(self):
143
+ return self.mask.sum()
144
+
145
+ def bbox(self):
146
+ p = mask_util.frPyObjects(self.polygons, self.height, self.width)
147
+ p = mask_util.merge(p)
148
+ bbox = mask_util.toBbox(p)
149
+ bbox[2] += bbox[0]
150
+ bbox[3] += bbox[1]
151
+ return bbox
152
+
153
+
154
+ class _PanopticPrediction:
155
+ """
156
+ Unify different panoptic annotation/prediction formats
157
+ """
158
+
159
+ def __init__(self, panoptic_seg, segments_info, metadata=None):
160
+ if segments_info is None:
161
+ assert metadata is not None
162
+ # If "segments_info" is None, we assume "panoptic_img" is a
163
+ # H*W int32 image storing the panoptic_id in the format of
164
+ # category_id * label_divisor + instance_id. We reserve -1 for
165
+ # VOID label.
166
+ label_divisor = metadata.label_divisor
167
+ segments_info = []
168
+ for panoptic_label in np.unique(panoptic_seg.numpy()):
169
+ if panoptic_label == -1:
170
+ # VOID region.
171
+ continue
172
+ pred_class = panoptic_label // label_divisor
173
+ isthing = pred_class in metadata.thing_dataset_id_to_contiguous_id.values()
174
+ segments_info.append(
175
+ {
176
+ "id": int(panoptic_label),
177
+ "category_id": int(pred_class),
178
+ "isthing": bool(isthing),
179
+ }
180
+ )
181
+ del metadata
182
+
183
+ self._seg = panoptic_seg
184
+
185
+ self._sinfo = {s["id"]: s for s in segments_info} # seg id -> seg info
186
+ segment_ids, areas = torch.unique(panoptic_seg, sorted=True, return_counts=True)
187
+ areas = areas.numpy()
188
+ sorted_idxs = np.argsort(-areas)
189
+ self._seg_ids, self._seg_areas = segment_ids[sorted_idxs], areas[sorted_idxs]
190
+ self._seg_ids = self._seg_ids.tolist()
191
+ for sid, area in zip(self._seg_ids, self._seg_areas):
192
+ if sid in self._sinfo:
193
+ self._sinfo[sid]["area"] = float(area)
194
+
195
+ def non_empty_mask(self):
196
+ """
197
+ Returns:
198
+ (H, W) array, a mask for all pixels that have a prediction
199
+ """
200
+ empty_ids = []
201
+ for id in self._seg_ids:
202
+ if id not in self._sinfo:
203
+ empty_ids.append(id)
204
+ if len(empty_ids) == 0:
205
+ return np.zeros(self._seg.shape, dtype=np.uint8)
206
+ assert (
207
+ len(empty_ids) == 1
208
+ ), ">1 ids corresponds to no labels. This is currently not supported"
209
+ return (self._seg != empty_ids[0]).numpy().astype(bool)
210
+
211
+ def semantic_masks(self):
212
+ for sid in self._seg_ids:
213
+ sinfo = self._sinfo.get(sid)
214
+ if sinfo is None or sinfo["isthing"]:
215
+ # Some pixels (e.g. id 0 in PanopticFPN) have no instance or semantic predictions.
216
+ continue
217
+ yield (self._seg == sid).numpy().astype(bool), sinfo
218
+
219
+ def instance_masks(self):
220
+ for sid in self._seg_ids:
221
+ sinfo = self._sinfo.get(sid)
222
+ if sinfo is None or not sinfo["isthing"]:
223
+ continue
224
+ mask = (self._seg == sid).numpy().astype(bool)
225
+ if mask.sum() > 0:
226
+ yield mask, sinfo
227
+
228
+
229
+ def _create_text_labels(classes, scores, class_names, is_crowd=None):
230
+ """
231
+ Args:
232
+ classes (list[int] or None):
233
+ scores (list[float] or None):
234
+ class_names (list[str] or None):
235
+ is_crowd (list[bool] or None):
236
+
237
+ Returns:
238
+ list[str] or None
239
+ """
240
+ labels = None
241
+ if classes is not None:
242
+ if class_names is not None and len(class_names) > 0:
243
+ labels = [class_names[i] for i in classes]
244
+ else:
245
+ labels = [str(i) for i in classes]
246
+ if scores is not None:
247
+ if labels is None:
248
+ # labels = ["{:.0f}%".format(s * 100) for s in scores]
249
+ labels = ["{:.2f}%".format(s) for s in scores]
250
+ else:
251
+ # labels = ["{} {:.0f}%".format(l, s * 100) for l, s in zip(labels, scores)]
252
+ labels = ["{} {:.2f}".format(l, s) for l, s in zip(labels, scores)]
253
+ if labels is not None and is_crowd is not None:
254
+ labels = [l + ("|crowd" if crowd else "") for l, crowd in zip(labels, is_crowd)]
255
+ return labels
256
+
257
+
258
+ class VisImage:
259
+ def __init__(self, img, scale=1.0):
260
+ """
261
+ Args:
262
+ img (ndarray): an RGB image of shape (H, W, 3) in range [0, 255].
263
+ scale (float): scale the input image
264
+ """
265
+ self.img = img
266
+ self.scale = scale
267
+ self.width, self.height = img.shape[1], img.shape[0]
268
+ self._setup_figure(img)
269
+
270
+ def _setup_figure(self, img):
271
+ """
272
+ Args:
273
+ Same as in :meth:`__init__()`.
274
+
275
+ Returns:
276
+ fig (matplotlib.pyplot.figure): top level container for all the image plot elements.
277
+ ax (matplotlib.pyplot.Axes): contains figure elements and sets the coordinate system.
278
+ """
279
+ fig = mplfigure.Figure(frameon=False)
280
+ self.dpi = fig.get_dpi()
281
+ # add a small 1e-2 to avoid precision lost due to matplotlib's truncation
282
+ # (https://github.com/matplotlib/matplotlib/issues/15363)
283
+ fig.set_size_inches(
284
+ (self.width * self.scale + 1e-2) / self.dpi,
285
+ (self.height * self.scale + 1e-2) / self.dpi,
286
+ )
287
+ self.canvas = FigureCanvasAgg(fig)
288
+ # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)
289
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
290
+ ax.axis("off")
291
+ self.fig = fig
292
+ self.ax = ax
293
+ self.reset_image(img)
294
+
295
+ def reset_image(self, img):
296
+ """
297
+ Args:
298
+ img: same as in __init__
299
+ """
300
+ img = img.astype("uint8")
301
+ self.ax.imshow(img, extent=(0, self.width, self.height, 0), interpolation="nearest")
302
+
303
+ def save(self, filepath):
304
+ """
305
+ Args:
306
+ filepath (str): a string that contains the absolute path, including the file name, where
307
+ the visualized image will be saved.
308
+ """
309
+ self.fig.savefig(filepath)
310
+
311
+ def get_image(self):
312
+ """
313
+ Returns:
314
+ ndarray:
315
+ the visualized image of shape (H, W, 3) (RGB) in uint8 type.
316
+ The shape is scaled w.r.t the input image using the given `scale` argument.
317
+ """
318
+ canvas = self.canvas
319
+ s, (width, height) = canvas.print_to_buffer()
320
+ # buf = io.BytesIO() # works for cairo backend
321
+ # canvas.print_rgba(buf)
322
+ # width, height = self.width, self.height
323
+ # s = buf.getvalue()
324
+
325
+ buffer = np.frombuffer(s, dtype="uint8")
326
+
327
+ img_rgba = buffer.reshape(height, width, 4)
328
+ rgb, alpha = np.split(img_rgba, [3], axis=2)
329
+ return rgb.astype("uint8")
330
+
331
+
332
+ class Visualizer:
333
+ """
334
+ Visualizer that draws data about detection/segmentation on images.
335
+
336
+ It contains methods like `draw_{text,box,circle,line,binary_mask,polygon}`
337
+ that draw primitive objects to images, as well as high-level wrappers like
338
+ `draw_{instance_predictions,sem_seg,panoptic_seg_predictions,dataset_dict}`
339
+ that draw composite data in some pre-defined style.
340
+
341
+ Note that the exact visualization style for the high-level wrappers are subject to change.
342
+ Style such as color, opacity, label contents, visibility of labels, or even the visibility
343
+ of objects themselves (e.g. when the object is too small) may change according
344
+ to different heuristics, as long as the results still look visually reasonable.
345
+
346
+ To obtain a consistent style, you can implement custom drawing functions with the
347
+ abovementioned primitive methods instead. If you need more customized visualization
348
+ styles, you can process the data yourself following their format documented in
349
+ tutorials (:doc:`/tutorials/models`, :doc:`/tutorials/datasets`). This class does not
350
+ intend to satisfy everyone's preference on drawing styles.
351
+
352
+ This visualizer focuses on high rendering quality rather than performance. It is not
353
+ designed to be used for real-time applications.
354
+ """
355
+
356
+ # TODO implement a fast, rasterized version using OpenCV
357
+
358
+ def __init__(self, img_rgb, metadata=None, scale=1.0, instance_mode=ColorMode.IMAGE):
359
+ """
360
+ Args:
361
+ img_rgb: a numpy array of shape (H, W, C), where H and W correspond to
362
+ the height and width of the image respectively. C is the number of
363
+ color channels. The image is required to be in RGB format since that
364
+ is a requirement of the Matplotlib library. The image is also expected
365
+ to be in the range [0, 255].
366
+ metadata (Metadata): dataset metadata (e.g. class names and colors)
367
+ instance_mode (ColorMode): defines one of the pre-defined style for drawing
368
+ instances on an image.
369
+ """
370
+ self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8)
371
+ if metadata is None:
372
+ metadata = MetadataCatalog.get("__nonexist__")
373
+ self.metadata = metadata
374
+ self.output = VisImage(self.img, scale=scale)
375
+ self.cpu_device = torch.device("cpu")
376
+
377
+ # too small texts are useless, therefore clamp to 9
378
+ self._default_font_size = max(
379
+ np.sqrt(self.output.height * self.output.width) // 90, 10 // scale
380
+ )
381
+ self._instance_mode = instance_mode
382
+ self.keypoint_threshold = _KEYPOINT_THRESHOLD
383
+
384
+ def draw_instance_predictions(self, predictions, keep_ids):
385
+ """
386
+ Draw instance-level prediction results on an image.
387
+
388
+ Args:
389
+ predictions (Instances): the output of an instance detection/segmentation
390
+ model. Following fields will be used to draw:
391
+ "pred_boxes", "pred_classes", "scores", "pred_masks" (or "pred_masks_rle").
392
+
393
+ Returns:
394
+ output (VisImage): image object with visualizations.
395
+ """
396
+ boxes = predictions.pred_boxes if predictions.has("pred_boxes") else None
397
+ scores = predictions.scores if predictions.has("scores") else None
398
+ classes = predictions.pred_classes.tolist() if predictions.has("pred_classes") else None
399
+ # labels = _create_text_labels(classes, scores, self.metadata.get("thing_classes", None))
400
+ labels = _create_text_labels(classes, scores, None)
401
+ keypoints = predictions.pred_keypoints if predictions.has("pred_keypoints") else None
402
+
403
+ if predictions.has("pred_masks"):
404
+ masks = np.asarray(predictions.pred_masks)
405
+ masks = [GenericMask(x, self.output.height, self.output.width) for x in masks]
406
+ else:
407
+ masks = None
408
+
409
+ if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get("thing_colors"):
410
+ colors = [[x / 255 for x in self.metadata.thing_colors[c]] for c in classes
411
+ ]
412
+ alpha = 1.0
413
+ else:
414
+ colors = None
415
+ alpha = 0.5
416
+
417
+ if self._instance_mode == ColorMode.IMAGE_BW:
418
+ self.output.reset_image(
419
+ self._create_grayscale_image(
420
+ (predictions.pred_masks.any(dim=0) > 0).numpy()
421
+ if predictions.has("pred_masks")
422
+ else None
423
+ )
424
+ )
425
+ alpha = 0.3
426
+
427
+ # print(len(keep_ids), len(boxes))
428
+ # labels = None
429
+ self.overlay_instances(
430
+ masks=masks,
431
+ boxes=boxes,
432
+ labels=labels,
433
+ keypoints=keypoints,
434
+ assigned_colors=colors,
435
+ alpha=1.0,
436
+ keep_ids=keep_ids,
437
+ )
438
+ return self.output
439
+
440
+ def draw_sem_seg(self, sem_seg, area_threshold=None, alpha=0.8):
441
+ """
442
+ Draw semantic segmentation predictions/labels.
443
+
444
+ Args:
445
+ sem_seg (Tensor or ndarray): the segmentation of shape (H, W).
446
+ Each value is the integer label of the pixel.
447
+ area_threshold (int): segments with less than `area_threshold` are not drawn.
448
+ alpha (float): the larger it is, the more opaque the segmentations are.
449
+
450
+ Returns:
451
+ output (VisImage): image object with visualizations.
452
+ """
453
+ if isinstance(sem_seg, torch.Tensor):
454
+ sem_seg = sem_seg.numpy()
455
+ labels, areas = np.unique(sem_seg, return_counts=True)
456
+ sorted_idxs = np.argsort(-areas).tolist()
457
+ labels = labels[sorted_idxs]
458
+ for label in filter(lambda l: l < len(self.metadata.stuff_classes), labels):
459
+ try:
460
+ mask_color = [x / 255 for x in self.metadata.stuff_colors[label]]
461
+ except (AttributeError, IndexError):
462
+ mask_color = None
463
+
464
+ binary_mask = (sem_seg == label).astype(np.uint8)
465
+ text = self.metadata.stuff_classes[label]
466
+ self.draw_binary_mask(
467
+ binary_mask,
468
+ color=mask_color,
469
+ edge_color=_OFF_WHITE,
470
+ text=text,
471
+ alpha=alpha,
472
+ area_threshold=area_threshold,
473
+ )
474
+ return self.output
475
+
476
+ def draw_panoptic_seg(self, panoptic_seg, segments_info, area_threshold=None, alpha=0.7):
477
+ """
478
+ Draw panoptic prediction annotations or results.
479
+
480
+ Args:
481
+ panoptic_seg (Tensor): of shape (height, width) where the values are ids for each
482
+ segment.
483
+ segments_info (list[dict] or None): Describe each segment in `panoptic_seg`.
484
+ If it is a ``list[dict]``, each dict contains keys "id", "category_id".
485
+ If None, category id of each pixel is computed by
486
+ ``pixel // metadata.label_divisor``.
487
+ area_threshold (int): stuff segments with less than `area_threshold` are not drawn.
488
+
489
+ Returns:
490
+ output (VisImage): image object with visualizations.
491
+ """
492
+ pred = _PanopticPrediction(panoptic_seg, segments_info, self.metadata)
493
+
494
+ if self._instance_mode == ColorMode.IMAGE_BW:
495
+ self.output.reset_image(self._create_grayscale_image(pred.non_empty_mask()))
496
+
497
+ # draw mask for all semantic segments first i.e. "stuff"
498
+ for mask, sinfo in pred.semantic_masks():
499
+ category_idx = sinfo["category_id"]
500
+ try:
501
+ mask_color = [x / 255 for x in self.metadata.stuff_colors[category_idx]]
502
+ except AttributeError:
503
+ mask_color = None
504
+
505
+ text = self.metadata.stuff_classes[category_idx]
506
+ self.draw_binary_mask(
507
+ mask,
508
+ color=mask_color,
509
+ edge_color=_OFF_WHITE,
510
+ text=text,
511
+ alpha=alpha,
512
+ area_threshold=area_threshold,
513
+ )
514
+
515
+ # draw mask for all instances second
516
+ all_instances = list(pred.instance_masks())
517
+ if len(all_instances) == 0:
518
+ return self.output
519
+ masks, sinfo = list(zip(*all_instances))
520
+ category_ids = [x["category_id"] for x in sinfo]
521
+
522
+ try:
523
+ scores = [x["score"] for x in sinfo]
524
+ except KeyError:
525
+ scores = None
526
+ labels = _create_text_labels(
527
+ category_ids, scores, self.metadata.thing_classes, [x.get("iscrowd", 0) for x in sinfo]
528
+ )
529
+
530
+ try:
531
+ colors = [
532
+ self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in category_ids
533
+ ]
534
+ except AttributeError:
535
+ colors = None
536
+ self.overlay_instances(masks=masks, labels=labels, assigned_colors=colors, alpha=alpha)
537
+
538
+ return self.output
539
+
540
+ draw_panoptic_seg_predictions = draw_panoptic_seg # backward compatibility
541
+
542
+ def draw_dataset_dict(self, dic, keep_ids=[]):
543
+ """
544
+ Draw annotations/segmentaions in Detectron2 Dataset format.
545
+
546
+ Args:
547
+ dic (dict): annotation/segmentation data of one image, in Detectron2 Dataset format.
548
+
549
+ Returns:
550
+ output (VisImage): image object with visualizations.
551
+ """
552
+ annos = dic.get("annotations", None)
553
+ if annos:
554
+ if "segmentation" in annos[0]:
555
+ masks = [x["segmentation"] for x in annos]
556
+ else:
557
+ masks = None
558
+ if "keypoints" in annos[0]:
559
+ keypts = [x["keypoints"] for x in annos]
560
+ keypts = np.array(keypts).reshape(len(annos), -1, 3)
561
+ else:
562
+ keypts = None
563
+
564
+ boxes = [
565
+ BoxMode.convert(x["bbox"], x["bbox_mode"], BoxMode.XYXY_ABS)
566
+ if len(x["bbox"]) == 4
567
+ else x["bbox"]
568
+ for x in annos
569
+ ]
570
+
571
+ colors = None
572
+ category_ids = [x["category_id"] for x in annos]
573
+ # if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get("thing_colors"):
574
+ # colors = [
575
+ # self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in category_ids
576
+ # ]
577
+ if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get("thing_colors"):
578
+ colors = [[x / 255 for x in self.metadata.thing_colors[c]] for c in category_ids]
579
+ names = self.metadata.get("thing_classes", None)
580
+ labels = _create_text_labels(
581
+ category_ids,
582
+ scores=None,
583
+ class_names=None,
584
+ is_crowd=[x.get("iscrowd", 0) for x in annos],
585
+ )
586
+ # labels = None
587
+ self.overlay_instances(
588
+ labels=labels, boxes=boxes, masks=masks, keypoints=keypts, assigned_colors=colors,
589
+ alpha=1.0, keep_ids=keep_ids
590
+ )
591
+
592
+ sem_seg = dic.get("sem_seg", None)
593
+ if sem_seg is None and "sem_seg_file_name" in dic:
594
+ with PathManager.open(dic["sem_seg_file_name"], "rb") as f:
595
+ sem_seg = Image.open(f)
596
+ sem_seg = np.asarray(sem_seg, dtype="uint8")
597
+ if sem_seg is not None:
598
+ self.draw_sem_seg(sem_seg, area_threshold=0, alpha=0.5)
599
+
600
+ pan_seg = dic.get("pan_seg", None)
601
+ if pan_seg is None and "pan_seg_file_name" in dic:
602
+ with PathManager.open(dic["pan_seg_file_name"], "rb") as f:
603
+ pan_seg = Image.open(f)
604
+ pan_seg = np.asarray(pan_seg)
605
+ from panopticapi.utils import rgb2id
606
+
607
+ pan_seg = rgb2id(pan_seg)
608
+ if pan_seg is not None:
609
+ segments_info = dic["segments_info"]
610
+ pan_seg = torch.tensor(pan_seg)
611
+ self.draw_panoptic_seg(pan_seg, segments_info, area_threshold=0, alpha=0.5)
612
+ return self.output
613
+
614
+ def overlay_instances(
615
+ self,
616
+ *,
617
+ boxes=None,
618
+ labels=None,
619
+ masks=None,
620
+ keypoints=None,
621
+ assigned_colors=None,
622
+ alpha=1.0,
623
+ keep_ids=[]
624
+ ):
625
+ """
626
+ Args:
627
+ boxes (Boxes, RotatedBoxes or ndarray): either a :class:`Boxes`,
628
+ or an Nx4 numpy array of XYXY_ABS format for the N objects in a single image,
629
+ or a :class:`RotatedBoxes`,
630
+ or an Nx5 numpy array of (x_center, y_center, width, height, angle_degrees) format
631
+ for the N objects in a single image,
632
+ labels (list[str]): the text to be displayed for each instance.
633
+ masks (masks-like object): Supported types are:
634
+
635
+ * :class:`detectron2.structures.PolygonMasks`,
636
+ :class:`detectron2.structures.BitMasks`.
637
+ * list[list[ndarray]]: contains the segmentation masks for all objects in one image.
638
+ The first level of the list corresponds to individual instances. The second
639
+ level to all the polygon that compose the instance, and the third level
640
+ to the polygon coordinates. The third level should have the format of
641
+ [x0, y0, x1, y1, ..., xn, yn] (n >= 3).
642
+ * list[ndarray]: each ndarray is a binary mask of shape (H, W).
643
+ * list[dict]: each dict is a COCO-style RLE.
644
+ keypoints (Keypoint or array like): an array-like object of shape (N, K, 3),
645
+ where the N is the number of instances and K is the number of keypoints.
646
+ The last dimension corresponds to (x, y, visibility or score).
647
+ assigned_colors (list[matplotlib.colors]): a list of colors, where each color
648
+ corresponds to each mask or box in the image. Refer to 'matplotlib.colors'
649
+ for full list of formats that the colors are accepted in.
650
+ Returns:
651
+ output (VisImage): image object with visualizations.
652
+ """
653
+ num_instances = 0
654
+ if boxes is not None:
655
+ boxes = self._convert_boxes(boxes)
656
+ num_instances = len(boxes)
657
+ if masks is not None:
658
+ masks = self._convert_masks(masks)
659
+ if num_instances:
660
+ assert len(masks) == num_instances
661
+ else:
662
+ num_instances = len(masks)
663
+ if keypoints is not None:
664
+ if num_instances:
665
+ assert len(keypoints) == num_instances
666
+ else:
667
+ num_instances = len(keypoints)
668
+ keypoints = self._convert_keypoints(keypoints)
669
+ if labels is not None:
670
+ assert len(labels) == num_instances
671
+ if assigned_colors is None:
672
+ assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)]
673
+ if num_instances == 0:
674
+ return self.output
675
+ if boxes is not None and boxes.shape[1] == 5:
676
+ return self.overlay_rotated_instances(
677
+ boxes=boxes, labels=labels, assigned_colors=assigned_colors
678
+ )
679
+
680
+ # Display in largest to smallest order to reduce occlusion.
681
+ areas = None
682
+ if boxes is not None:
683
+ areas = np.prod(boxes[:, 2:] - boxes[:, :2], axis=1)
684
+ elif masks is not None:
685
+ areas = np.asarray([x.area() for x in masks])
686
+
687
+ if areas is not None:
688
+ sorted_idxs = np.argsort(-areas).tolist()
689
+ # Re-order overlapped instances in descending order.
690
+ boxes = boxes[sorted_idxs] if boxes is not None else None
691
+ labels = [labels[k] for k in sorted_idxs] if labels is not None else None
692
+ masks = [masks[idx] for idx in sorted_idxs] if masks is not None else None
693
+ assigned_colors = [assigned_colors[idx] for idx in sorted_idxs]
694
+ keypoints = keypoints[sorted_idxs] if keypoints is not None else None
695
+
696
+ if len(keep_ids) == 0:
697
+ keep_ids = [*range(num_instances)]
698
+
699
+ for i in range(num_instances):
700
+ if sorted_idxs[i] not in keep_ids:
701
+ print('\t', sorted_idxs[i])
702
+ continue
703
+ color = assigned_colors[i]
704
+ if boxes is not None:
705
+ self.draw_box(boxes[i], edge_color=color)
706
+
707
+ if masks is not None:
708
+ for segment in masks[i].polygons:
709
+ self.draw_polygon(segment.reshape(-1, 2), color, alpha=alpha)
710
+
711
+ if labels is not None:
712
+ # first get a box
713
+ if boxes is not None:
714
+ x0, y0, x1, y1 = boxes[i]
715
+ text_pos = (x0-10, y0-30) # if drawing boxes, put text on the box corner.
716
+ horiz_align = "left"
717
+ elif masks is not None:
718
+ # skip small mask without polygon
719
+ if len(masks[i].polygons) == 0:
720
+ continue
721
+
722
+ x0, y0, x1, y1 = masks[i].bbox()
723
+
724
+ # draw text in the center (defined by median) when box is not drawn
725
+ # median is less sensitive to outliers.
726
+ text_pos = np.median(masks[i].mask.nonzero(), axis=1)[::-1]
727
+ horiz_align = "center"
728
+ else:
729
+ continue # drawing the box confidence for keypoints isn't very useful.
730
+ # for small objects, draw text at the side to avoid occlusion
731
+ instance_area = (y1 - y0) * (x1 - x0)
732
+ if (
733
+ instance_area < _SMALL_OBJECT_AREA_THRESH * self.output.scale
734
+ or y1 - y0 < 40 * self.output.scale
735
+ ):
736
+ if y1 >= self.output.height - 5:
737
+ text_pos = (x1, y0)
738
+ else:
739
+ text_pos = (x0, y1)
740
+
741
+ height_ratio = (y1 - y0) / np.sqrt(self.output.height * self.output.width)
742
+ lighter_color = self._change_color_brightness(color, brightness_factor=0.7)
743
+ # font_size = (
744
+ # np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2)
745
+ # * 0.5
746
+ # * self._default_font_size
747
+ # )
748
+ font_size = 18
749
+ self.draw_text(
750
+ labels[i],
751
+ text_pos,
752
+ color=lighter_color,
753
+ horizontal_alignment=horiz_align,
754
+ font_size=font_size,
755
+ )
756
+
757
+ # draw keypoints
758
+ if keypoints is not None:
759
+ for keypoints_per_instance in keypoints:
760
+ self.draw_and_connect_keypoints(keypoints_per_instance)
761
+
762
+ return self.output
763
+
764
+ def overlay_rotated_instances(self, boxes=None, labels=None, assigned_colors=None):
765
+ """
766
+ Args:
767
+ boxes (ndarray): an Nx5 numpy array of
768
+ (x_center, y_center, width, height, angle_degrees) format
769
+ for the N objects in a single image.
770
+ labels (list[str]): the text to be displayed for each instance.
771
+ assigned_colors (list[matplotlib.colors]): a list of colors, where each color
772
+ corresponds to each mask or box in the image. Refer to 'matplotlib.colors'
773
+ for full list of formats that the colors are accepted in.
774
+
775
+ Returns:
776
+ output (VisImage): image object with visualizations.
777
+ """
778
+ num_instances = len(boxes)
779
+
780
+ if assigned_colors is None:
781
+ assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)]
782
+ if num_instances == 0:
783
+ return self.output
784
+
785
+ # Display in largest to smallest order to reduce occlusion.
786
+ if boxes is not None:
787
+ areas = boxes[:, 2] * boxes[:, 3]
788
+
789
+ sorted_idxs = np.argsort(-areas).tolist()
790
+ # Re-order overlapped instances in descending order.
791
+ boxes = boxes[sorted_idxs]
792
+ labels = [labels[k] for k in sorted_idxs] if labels is not None else None
793
+ colors = [assigned_colors[idx] for idx in sorted_idxs]
794
+
795
+ for i in range(num_instances):
796
+ self.draw_rotated_box_with_label(
797
+ boxes[i], edge_color=colors[i], label=labels[i] if labels is not None else None
798
+ )
799
+
800
+ return self.output
801
+
802
+ def draw_and_connect_keypoints(self, keypoints):
803
+ """
804
+ Draws keypoints of an instance and follows the rules for keypoint connections
805
+ to draw lines between appropriate keypoints. This follows color heuristics for
806
+ line color.
807
+
808
+ Args:
809
+ keypoints (Tensor): a tensor of shape (K, 3), where K is the number of keypoints
810
+ and the last dimension corresponds to (x, y, probability).
811
+
812
+ Returns:
813
+ output (VisImage): image object with visualizations.
814
+ """
815
+ visible = {}
816
+ keypoint_names = self.metadata.get("keypoint_names")
817
+ for idx, keypoint in enumerate(keypoints):
818
+
819
+ # draw keypoint
820
+ x, y, prob = keypoint
821
+ if prob > self.keypoint_threshold:
822
+ self.draw_circle((x, y), color=_RED)
823
+ if keypoint_names:
824
+ keypoint_name = keypoint_names[idx]
825
+ visible[keypoint_name] = (x, y)
826
+
827
+ if self.metadata.get("keypoint_connection_rules"):
828
+ for kp0, kp1, color in self.metadata.keypoint_connection_rules:
829
+ if kp0 in visible and kp1 in visible:
830
+ x0, y0 = visible[kp0]
831
+ x1, y1 = visible[kp1]
832
+ color = tuple(x / 255.0 for x in color)
833
+ self.draw_line([x0, x1], [y0, y1], color=color)
834
+
835
+ # draw lines from nose to mid-shoulder and mid-shoulder to mid-hip
836
+ # Note that this strategy is specific to person keypoints.
837
+ # For other keypoints, it should just do nothing
838
+ try:
839
+ ls_x, ls_y = visible["left_shoulder"]
840
+ rs_x, rs_y = visible["right_shoulder"]
841
+ mid_shoulder_x, mid_shoulder_y = (ls_x + rs_x) / 2, (ls_y + rs_y) / 2
842
+ except KeyError:
843
+ pass
844
+ else:
845
+ # draw line from nose to mid-shoulder
846
+ nose_x, nose_y = visible.get("nose", (None, None))
847
+ if nose_x is not None:
848
+ self.draw_line([nose_x, mid_shoulder_x], [nose_y, mid_shoulder_y], color=_RED)
849
+
850
+ try:
851
+ # draw line from mid-shoulder to mid-hip
852
+ lh_x, lh_y = visible["left_hip"]
853
+ rh_x, rh_y = visible["right_hip"]
854
+ except KeyError:
855
+ pass
856
+ else:
857
+ mid_hip_x, mid_hip_y = (lh_x + rh_x) / 2, (lh_y + rh_y) / 2
858
+ self.draw_line([mid_hip_x, mid_shoulder_x], [mid_hip_y, mid_shoulder_y], color=_RED)
859
+ return self.output
860
+
861
+ """
862
+ Primitive drawing functions:
863
+ """
864
+
865
+ def draw_text(
866
+ self,
867
+ text,
868
+ position,
869
+ *,
870
+ font_size=None,
871
+ color="g",
872
+ horizontal_alignment="center",
873
+ rotation=0,
874
+ ):
875
+ """
876
+ Args:
877
+ text (str): class label
878
+ position (tuple): a tuple of the x and y coordinates to place text on image.
879
+ font_size (int, optional): font of the text. If not provided, a font size
880
+ proportional to the image width is calculated and used.
881
+ color: color of the text. Refer to `matplotlib.colors` for full list
882
+ of formats that are accepted.
883
+ horizontal_alignment (str): see `matplotlib.text.Text`
884
+ rotation: rotation angle in degrees CCW
885
+
886
+ Returns:
887
+ output (VisImage): image object with text drawn.
888
+ """
889
+ if not font_size:
890
+ font_size = self._default_font_size
891
+
892
+ # since the text background is dark, we don't want the text to be dark
893
+ color = np.maximum(list(mplc.to_rgb(color)), 0.2)
894
+ color[np.argmax(color)] = max(0.8, np.max(color))
895
+
896
+ x, y = position
897
+ self.output.ax.text(
898
+ x,
899
+ y,
900
+ text,
901
+ size=font_size * self.output.scale,
902
+ family="sans-serif",
903
+ bbox={"facecolor": "black", "alpha": 0.8, "pad": 0.7, "edgecolor": "none"},
904
+ verticalalignment="top",
905
+ horizontalalignment=horizontal_alignment,
906
+ color=color,
907
+ zorder=10,
908
+ rotation=rotation,
909
+ )
910
+ return self.output
911
+
912
+ def draw_box(self, box_coord, alpha=0.5, edge_color="g", line_style="-"):
913
+ """
914
+ Args:
915
+ box_coord (tuple): a tuple containing x0, y0, x1, y1 coordinates, where x0 and y0
916
+ are the coordinates of the image's top left corner. x1 and y1 are the
917
+ coordinates of the image's bottom right corner.
918
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
919
+ edge_color: color of the outline of the box. Refer to `matplotlib.colors`
920
+ for full list of formats that are accepted.
921
+ line_style (string): the string to use to create the outline of the boxes.
922
+
923
+ Returns:
924
+ output (VisImage): image object with box drawn.
925
+ """
926
+ x0, y0, x1, y1 = box_coord
927
+ width = x1 - x0
928
+ height = y1 - y0
929
+
930
+ # linewidth = max(self._default_font_size / 4, 1)
931
+ linewidth = 10
932
+
933
+ self.output.ax.add_patch(
934
+ mpl.patches.Rectangle(
935
+ (x0, y0),
936
+ width,
937
+ height,
938
+ fill=False,
939
+ edgecolor=edge_color,
940
+ linewidth=linewidth * self.output.scale,
941
+ alpha=alpha,
942
+ linestyle=line_style,
943
+ )
944
+ )
945
+ return self.output
946
+
947
+ def draw_rotated_box_with_label(
948
+ self, rotated_box, alpha=0.5, edge_color="g", line_style="-", label=None
949
+ ):
950
+ """
951
+ Draw a rotated box with label on its top-left corner.
952
+
953
+ Args:
954
+ rotated_box (tuple): a tuple containing (cnt_x, cnt_y, w, h, angle),
955
+ where cnt_x and cnt_y are the center coordinates of the box.
956
+ w and h are the width and height of the box. angle represents how
957
+ many degrees the box is rotated CCW with regard to the 0-degree box.
958
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
959
+ edge_color: color of the outline of the box. Refer to `matplotlib.colors`
960
+ for full list of formats that are accepted.
961
+ line_style (string): the string to use to create the outline of the boxes.
962
+ label (string): label for rotated box. It will not be rendered when set to None.
963
+
964
+ Returns:
965
+ output (VisImage): image object with box drawn.
966
+ """
967
+ cnt_x, cnt_y, w, h, angle = rotated_box
968
+ area = w * h
969
+ # use thinner lines when the box is small
970
+ linewidth = self._default_font_size / (
971
+ 6 if area < _SMALL_OBJECT_AREA_THRESH * self.output.scale else 3
972
+ )
973
+
974
+ theta = angle * math.pi / 180.0
975
+ c = math.cos(theta)
976
+ s = math.sin(theta)
977
+ rect = [(-w / 2, h / 2), (-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2)]
978
+ # x: left->right ; y: top->down
979
+ rotated_rect = [(s * yy + c * xx + cnt_x, c * yy - s * xx + cnt_y) for (xx, yy) in rect]
980
+ for k in range(4):
981
+ j = (k + 1) % 4
982
+ self.draw_line(
983
+ [rotated_rect[k][0], rotated_rect[j][0]],
984
+ [rotated_rect[k][1], rotated_rect[j][1]],
985
+ color=edge_color,
986
+ linestyle="--" if k == 1 else line_style,
987
+ linewidth=linewidth,
988
+ )
989
+
990
+ if label is not None:
991
+ text_pos = rotated_rect[1] # topleft corner
992
+
993
+ height_ratio = h / np.sqrt(self.output.height * self.output.width)
994
+ label_color = self._change_color_brightness(edge_color, brightness_factor=0.7)
995
+ font_size = (
996
+ np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2) * 0.5 * self._default_font_size
997
+ )
998
+ self.draw_text(label, text_pos, color=label_color, font_size=font_size, rotation=angle)
999
+
1000
+ return self.output
1001
+
1002
+ def draw_circle(self, circle_coord, color, radius=3):
1003
+ """
1004
+ Args:
1005
+ circle_coord (list(int) or tuple(int)): contains the x and y coordinates
1006
+ of the center of the circle.
1007
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
1008
+ formats that are accepted.
1009
+ radius (int): radius of the circle.
1010
+
1011
+ Returns:
1012
+ output (VisImage): image object with box drawn.
1013
+ """
1014
+ x, y = circle_coord
1015
+ self.output.ax.add_patch(
1016
+ mpl.patches.Circle(circle_coord, radius=radius, fill=False, color=color)
1017
+ )
1018
+ return self.output
1019
+
1020
+ def draw_line(self, x_data, y_data, color, linestyle="-", linewidth=None):
1021
+ """
1022
+ Args:
1023
+ x_data (list[int]): a list containing x values of all the points being drawn.
1024
+ Length of list should match the length of y_data.
1025
+ y_data (list[int]): a list containing y values of all the points being drawn.
1026
+ Length of list should match the length of x_data.
1027
+ color: color of the line. Refer to `matplotlib.colors` for a full list of
1028
+ formats that are accepted.
1029
+ linestyle: style of the line. Refer to `matplotlib.lines.Line2D`
1030
+ for a full list of formats that are accepted.
1031
+ linewidth (float or None): width of the line. When it's None,
1032
+ a default value will be computed and used.
1033
+
1034
+ Returns:
1035
+ output (VisImage): image object with line drawn.
1036
+ """
1037
+ if linewidth is None:
1038
+ linewidth = self._default_font_size / 3
1039
+ linewidth = max(linewidth, 1)
1040
+ self.output.ax.add_line(
1041
+ mpl.lines.Line2D(
1042
+ x_data,
1043
+ y_data,
1044
+ linewidth=linewidth * self.output.scale,
1045
+ color=color,
1046
+ linestyle=linestyle,
1047
+ )
1048
+ )
1049
+ return self.output
1050
+
1051
+ def draw_binary_mask(
1052
+ self, binary_mask, color=None, *, edge_color=None, text=None, alpha=0.5, area_threshold=10
1053
+ ):
1054
+ """
1055
+ Args:
1056
+ binary_mask (ndarray): numpy array of shape (H, W), where H is the image height and
1057
+ W is the image width. Each value in the array is either a 0 or 1 value of uint8
1058
+ type.
1059
+ color: color of the mask. Refer to `matplotlib.colors` for a full list of
1060
+ formats that are accepted. If None, will pick a random color.
1061
+ edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a
1062
+ full list of formats that are accepted.
1063
+ text (str): if None, will be drawn on the object
1064
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1065
+ area_threshold (float): a connected component smaller than this area will not be shown.
1066
+
1067
+ Returns:
1068
+ output (VisImage): image object with mask drawn.
1069
+ """
1070
+ if color is None:
1071
+ color = random_color(rgb=True, maximum=1)
1072
+ color = mplc.to_rgb(color)
1073
+
1074
+ has_valid_segment = False
1075
+ binary_mask = binary_mask.astype("uint8") # opencv needs uint8
1076
+ mask = GenericMask(binary_mask, self.output.height, self.output.width)
1077
+ shape2d = (binary_mask.shape[0], binary_mask.shape[1])
1078
+
1079
+ if not mask.has_holes:
1080
+ # draw polygons for regular masks
1081
+ for segment in mask.polygons:
1082
+ area = mask_util.area(mask_util.frPyObjects([segment], shape2d[0], shape2d[1]))
1083
+ if area < (area_threshold or 0):
1084
+ continue
1085
+ has_valid_segment = True
1086
+ segment = segment.reshape(-1, 2)
1087
+ self.draw_polygon(segment, color=color, edge_color=edge_color, alpha=alpha)
1088
+ else:
1089
+ # TODO: Use Path/PathPatch to draw vector graphics:
1090
+ # https://stackoverflow.com/questions/8919719/how-to-plot-a-complex-polygon
1091
+ rgba = np.zeros(shape2d + (4,), dtype="float32")
1092
+ rgba[:, :, :3] = color
1093
+ rgba[:, :, 3] = (mask.mask == 1).astype("float32") * alpha
1094
+ has_valid_segment = True
1095
+ self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0))
1096
+
1097
+ if text is not None and has_valid_segment:
1098
+ lighter_color = self._change_color_brightness(color, brightness_factor=0.7)
1099
+ self._draw_text_in_mask(binary_mask, text, lighter_color)
1100
+ return self.output
1101
+
1102
+ def draw_soft_mask(self, soft_mask, color=None, *, text=None, alpha=0.5):
1103
+ """
1104
+ Args:
1105
+ soft_mask (ndarray): float array of shape (H, W), each value in [0, 1].
1106
+ color: color of the mask. Refer to `matplotlib.colors` for a full list of
1107
+ formats that are accepted. If None, will pick a random color.
1108
+ text (str): if None, will be drawn on the object
1109
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1110
+
1111
+ Returns:
1112
+ output (VisImage): image object with mask drawn.
1113
+ """
1114
+ if color is None:
1115
+ color = random_color(rgb=True, maximum=1)
1116
+ color = mplc.to_rgb(color)
1117
+
1118
+ shape2d = (soft_mask.shape[0], soft_mask.shape[1])
1119
+ rgba = np.zeros(shape2d + (4,), dtype="float32")
1120
+ rgba[:, :, :3] = color
1121
+ rgba[:, :, 3] = soft_mask * alpha
1122
+ self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0))
1123
+
1124
+ if text is not None:
1125
+ lighter_color = self._change_color_brightness(color, brightness_factor=0.7)
1126
+ binary_mask = (soft_mask > 0.5).astype("uint8")
1127
+ self._draw_text_in_mask(binary_mask, text, lighter_color)
1128
+ return self.output
1129
+
1130
+ def draw_polygon(self, segment, color, edge_color=None, alpha=1.0):
1131
+ """
1132
+ Args:
1133
+ segment: numpy array of shape Nx2, containing all the points in the polygon.
1134
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
1135
+ formats that are accepted.
1136
+ edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a
1137
+ full list of formats that are accepted. If not provided, a darker shade
1138
+ of the polygon color will be used instead.
1139
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1140
+
1141
+ Returns:
1142
+ output (VisImage): image object with polygon drawn.
1143
+ """
1144
+ if edge_color is None:
1145
+ # make edge color darker than the polygon color
1146
+ if alpha > 0.8:
1147
+ edge_color = self._change_color_brightness(color, brightness_factor=-0.7)
1148
+ else:
1149
+ edge_color = color
1150
+ edge_color = mplc.to_rgb(edge_color) + (1,)
1151
+
1152
+ polygon = mpl.patches.Polygon(
1153
+ segment,
1154
+ fill=False,
1155
+ facecolor=mplc.to_rgb(color) + (alpha,),
1156
+ edgecolor=edge_color,
1157
+ linewidth=max(self._default_font_size // 15 * self.output.scale, 1),
1158
+ )
1159
+ self.output.ax.add_patch(polygon)
1160
+ return self.output
1161
+
1162
+ """
1163
+ Internal methods:
1164
+ """
1165
+
1166
+ def _jitter(self, color):
1167
+ """
1168
+ Randomly modifies given color to produce a slightly different color than the color given.
1169
+
1170
+ Args:
1171
+ color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color
1172
+ picked. The values in the list are in the [0.0, 1.0] range.
1173
+
1174
+ Returns:
1175
+ jittered_color (tuple[double]): a tuple of 3 elements, containing the RGB values of the
1176
+ color after being jittered. The values in the list are in the [0.0, 1.0] range.
1177
+ """
1178
+ color = mplc.to_rgb(color)
1179
+ vec = np.random.rand(3)
1180
+ # better to do it in another color space
1181
+ vec = vec / np.linalg.norm(vec) * 0.5
1182
+ res = np.clip(vec + color, 0, 1)
1183
+ return tuple(res)
1184
+
1185
+ def _create_grayscale_image(self, mask=None):
1186
+ """
1187
+ Create a grayscale version of the original image.
1188
+ The colors in masked area, if given, will be kept.
1189
+ """
1190
+ img_bw = self.img.astype("f4").mean(axis=2)
1191
+ img_bw = np.stack([img_bw] * 3, axis=2)
1192
+ if mask is not None:
1193
+ img_bw[mask] = self.img[mask]
1194
+ return img_bw
1195
+
1196
+ def _change_color_brightness(self, color, brightness_factor):
1197
+ """
1198
+ Depending on the brightness_factor, gives a lighter or darker color i.e. a color with
1199
+ less or more saturation than the original color.
1200
+
1201
+ Args:
1202
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
1203
+ formats that are accepted.
1204
+ brightness_factor (float): a value in [-1.0, 1.0] range. A lightness factor of
1205
+ 0 will correspond to no change, a factor in [-1.0, 0) range will result in
1206
+ a darker color and a factor in (0, 1.0] range will result in a lighter color.
1207
+
1208
+ Returns:
1209
+ modified_color (tuple[double]): a tuple containing the RGB values of the
1210
+ modified color. Each value in the tuple is in the [0.0, 1.0] range.
1211
+ """
1212
+ assert brightness_factor >= -1.0 and brightness_factor <= 1.0
1213
+ color = mplc.to_rgb(color)
1214
+ polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color))
1215
+ modified_lightness = polygon_color[1] + (brightness_factor * polygon_color[1])
1216
+ modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness
1217
+ modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness
1218
+ modified_color = colorsys.hls_to_rgb(polygon_color[0], modified_lightness, polygon_color[2])
1219
+ return modified_color
1220
+
1221
+ def _convert_boxes(self, boxes):
1222
+ """
1223
+ Convert different format of boxes to an NxB array, where B = 4 or 5 is the box dimension.
1224
+ """
1225
+ if isinstance(boxes, Boxes) or isinstance(boxes, RotatedBoxes):
1226
+ return boxes.tensor.detach().numpy()
1227
+ else:
1228
+ return np.asarray(boxes)
1229
+
1230
+ def _convert_masks(self, masks_or_polygons):
1231
+ """
1232
+ Convert different format of masks or polygons to a tuple of masks and polygons.
1233
+
1234
+ Returns:
1235
+ list[GenericMask]:
1236
+ """
1237
+
1238
+ m = masks_or_polygons
1239
+ if isinstance(m, PolygonMasks):
1240
+ m = m.polygons
1241
+ if isinstance(m, BitMasks):
1242
+ m = m.tensor.numpy()
1243
+ if isinstance(m, torch.Tensor):
1244
+ m = m.numpy()
1245
+ ret = []
1246
+ for x in m:
1247
+ if isinstance(x, GenericMask):
1248
+ ret.append(x)
1249
+ else:
1250
+ ret.append(GenericMask(x, self.output.height, self.output.width))
1251
+ return ret
1252
+
1253
+ def _draw_text_in_mask(self, binary_mask, text, color):
1254
+ """
1255
+ Find proper places to draw text given a binary mask.
1256
+ """
1257
+ # TODO sometimes drawn on wrong objects. the heuristics here can improve.
1258
+ _num_cc, cc_labels, stats, centroids = cv2.connectedComponentsWithStats(binary_mask, 8)
1259
+ if stats[1:, -1].size == 0:
1260
+ return
1261
+ largest_component_id = np.argmax(stats[1:, -1]) + 1
1262
+
1263
+ # draw text on the largest component, as well as other very large components.
1264
+ for cid in range(1, _num_cc):
1265
+ if cid == largest_component_id or stats[cid, -1] > _LARGE_MASK_AREA_THRESH:
1266
+ # median is more stable than centroid
1267
+ # center = centroids[largest_component_id]
1268
+ center = np.median((cc_labels == cid).nonzero(), axis=1)[::-1]
1269
+ self.draw_text(text, center, color=color)
1270
+
1271
+ def _convert_keypoints(self, keypoints):
1272
+ if isinstance(keypoints, Keypoints):
1273
+ keypoints = keypoints.tensor
1274
+ keypoints = np.asarray(keypoints)
1275
+ return keypoints
1276
+
1277
+ def get_output(self):
1278
+ """
1279
+ Returns:
1280
+ output (VisImage): the image output containing the visualizations added
1281
+ to the image.
1282
+ """
1283
+ return self.output