File size: 18,202 Bytes
07444d1 | 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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | import json
import argparse
from os.path import join
import copy
import os
from glob import glob
import numpy as np
import cv2
from shapely.geometry import box, Polygon
from shapely.validation import make_valid
def main(args):
subset_jsons = dict()
input_id = os.path.basename(args.input).split('.')[0]
addition_id = input_id + '_addition'
subset_jsons[input_id] = dict()
subset_jsons[input_id]['filename'] = args.input
subset_jsons[input_id]['dataset'] = args.dataset
subset_jsons[input_id]['subset'] = args.subset
if args.addition:
subset_jsons[addition_id] = dict()
subset_jsons[addition_id]['filename'] = args.addition
subset_jsons[addition_id]['dataset'] = args.dataset
subset_jsons[addition_id]['subset'] = args.subset
image_files = glob(join(args.dataset_folder,'**/*.jpg'), recursive = True)
if args.dataset in ['cnr', 'plds']:
image_files = [x for x in image_files if args.subset.lower() in x.lower()]
print(image_files)
image_dict = dict()
for i in range(len(image_files)):
image_files[i] = image_files[i].replace(args.dataset_folder, '')
if args.dataset == 'pklot':
image_files[i] = join(args.subset.upper(), image_files[i])
else:
image_files[i] = image_files[i]
image_id = os.path.split(image_files[i])[1]
if image_id in image_dict:
print(f'image {image_id} already exists')
else:
image_dict[image_id] = dict()
image_dict[image_id]['path'] = image_files[i]
# print(image_id)
image_dict[image_id]['json'] = False
print('image_dict' , len(image_dict))
new_data = generate_new_json(subset_jsons, args, image_dict)
with open(args.output, 'w') as f:
json.dump(new_data, f)
print('new data saved.')
def generate_new_json(subset_jsons, args, image_dict):
json_data = dict()
next_ids = dict()
next_ids['image'] = 1
next_ids['annotation'] = 1
next_ids['spot'] = 1
force_subscribe = False
rectangle = None
image_samples = dict()
for subset_json in subset_jsons.keys():
filename = subset_jsons[subset_json]['filename']
print(filename)
with open(filename) as json_file:
data = json.load(json_file)
# init data
if not json_data:
json_data['images'] = dict()
json_data['annotations'] = dict()
json_data['categories'] = data['categories']
json_data['parkingSpots'] = dict()
json_data['statuses'] = data['statuses']
json_data['climates'] = data['climates']
else:
force_subscribe = True
print('images keys', data['images'][0].keys())
print('annotations keys', data['annotations'][0].keys())
if 'parkingSpots' in data:
print('parkingSpots keys', data['parkingSpots'][0].keys())
images = data['images']
annotations = data['annotations']
if rectangle is None:
if args.rectangle:
rectangle = args.rectangle
else:
rectangle = images[0]['annotationsRectangle']
print(f'\t rectangle {rectangle}')
print(f'\t images size {len(images)}')
print(f'\t annotations size {len(annotations)}')
if 'parkingSpots' in data:
parkingSpots = data['parkingSpots']
print(f'\t parkingSpots size {len(parkingSpots)}')
else:
parkingSpots = None
copy_values(images, annotations, parkingSpots, json_data, next_ids, args.dataset, args.subset, image_dict, rectangle, image_samples, args.check_duplicates, force_subscribe)
print('...done.')
json_data['images'] = list(json_data['images'].values())
if args.add_absent_images:
for image_id in image_dict.keys():
if not image_dict[image_id]['json']:
image_dict[image_id]['json'] = True
new_image = dict()
new_image['id'] = next_ids['image']
new_image['file_name'] = image_dict[image_id]['path']
new_image['width'] = json_data['images'][0]['width']
new_image['height'] = json_data['images'][0]['height']
new_image['annotationsRectangle'] = rectangle
if any([weather in image_dict[image_id]['path'].lower() for weather in ['cloudy', 'overcast']]):
climate = 1
elif any([weather in image_dict[image_id]['path'].lower() for weather in ['sunny']]):
climate = 2
elif any([weather in image_dict[image_id]['path'].lower() for weather in ['rainy']]):
climate = 3
elif any([weather in image_dict[image_id]['path'].lower() for weather in ['snow']]):
climate = 4
elif any([weather in image_dict[image_id]['path'].lower() for weather in ['normal']]):
climate = 5
else:
climate = 6
if args.dataset.lower() == 'pklot':
date = image_dict[image_id]['path'].split('/')[-1]
date = date.replace('.jpg', '')
time = date.split('_')[1:]
date = date.split('_')[0]
date = date.split('-')
elif args.dataset.lower() == 'cnr':
date = image_dict[image_id]['path'].split('/')[-1]
date = date.replace('.jpg', '')
time = date.split('_')[1]
time = [time[:2], time[2:], '00']
date = date.split('_')[0]
date = date.split('-')
elif args.dataset.lower() == 'plds':
date = image_dict[image_id]['path'].split('/')[-2]
date = date.split('-')
time = None
else:
raise NotImplementedError
new_image['date'] = date # "date": [2015, 12, 18]
new_image['time'] = time # "time": [10, 17, 05]
new_image['climate'] = climate
new_image['dataset'] = args.dataset
new_image['subset'] = args.subset
print(f'\t image {image_id} added with path {new_image["file_name"]}')
print(f'\t{new_image}')
json_data['images'].append(new_image)
next_ids['image'] += 1
json_data['annotations'] = list(json_data['annotations'].values())
json_data['parkingSpots'] = list(json_data['parkingSpots'].values())
print(next_ids)
return json_data
def get_largest_poly_from_self_intersection(coords):
poly = Polygon(coords)
if poly.is_valid:
return poly
mp = make_valid(poly)
if type(mp) == Polygon:
return mp
largest_poly = max(mp.geoms, key=lambda p: p.area)
print('largest_poly.area, mp.area', largest_poly.area, mp.area)
return largest_poly
def copy_values(images, annotations, parkingSpots, json_data, next_ids, dataset, subset, image_dict, rectangle, image_samples, check_duplicates, force_subscribe):
perc = -1
for i in range(len(images)):
image = copy.deepcopy(images[i])
new_perc = int(i/len(images)*100)
if new_perc > perc:
perc = new_perc
print(f'{perc}% - current image id: {next_ids["image"]}')
annotations_list = [copy.deepcopy(x) for x in annotations if x['image_id'] == image['id']]
if parkingSpots:
spots_list = [copy.deepcopy(x) for x in parkingSpots if x['image_id'] == image['id']]
if 'path' in image:
baseline = os.path.split(image_dict[image['file_name']]['path'])[1]
image['file_name'] = image_dict[baseline]['path']
image_dict[baseline]['json'] = True
else:
baseline = os.path.split(image['file_name'])[1]
image['file_name'] = image_dict[baseline]['path']
image_dict[baseline]['json'] = True
if image['file_name'] in json_data['images']: # if image already exists in json
image = json_data['images'][image['file_name']]
if force_subscribe:
if annotations_list:
for j in image_samples[image['id']]['annotation_ids']:
json_data['annotations'].pop(j, None)
image_samples[image['id']]['annotation_ids'] = list()
if parkingSpots and spots_list:
for j in image_samples[image['id']]['spot_ids']:
json_data['parkingSpots'].pop(j, None)
image_samples[image['id']]['spot_ids'] = list()
else: # if image does not exist in json
image['id'] = next_ids['image']
image_samples[image['id']] = dict()
image_samples[image['id']]['annotation_ids'] = list()
image_samples[image['id']]['spot_ids'] = list()
next_ids['image'] += 1
image['dataset'] = dataset
image['subset'] = subset
if rectangle:
image['annotationsRectangle'] = rectangle
image.pop('dataset_id', None)
image.pop('category_ids', None)
image.pop('path', None)
image.pop('annotated', None)
image.pop('annotating', None)
image.pop('num_annotations', None)
image.pop('metadata', None)
image.pop('deleted', None)
image.pop('milliseconds', None)
image.pop('regenerate_thumbnail', None)
for annotation in annotations_list:
annotation.pop('isbbox', None)
annotation.pop('color', None)
annotation.pop('metadata', None)
new_seg = list()
for ann in annotation['segmentation']:
coords = np.reshape(ann, (-1, 2))
coords = np.int32(coords) # Convert to int32 to fillPoly function
# remove small polygons
if cv2.contourArea(coords) < 10:
print('poly area', cv2.contourArea(coords), 'removed')
elif check_duplicates:
cur_poly = get_largest_poly_from_self_intersection(coords)
no_intersection = True
try:
# check if current mask intersects with any other polygon
for saved_annotation_id in image_samples[image['id']]['annotation_ids']:
saved_annotation = json_data['annotations'][saved_annotation_id]
for i in range(len(saved_annotation['segmentation'])):
other_coords = np.reshape(saved_annotation['segmentation'][i], (-1, 2))
other_coords = np.int32(other_coords)
other_poly = get_largest_poly_from_self_intersection(other_coords)
polygon_intersection = cur_poly.intersection(other_poly).area
polygon_union = cur_poly.area + other_poly.area - polygon_intersection
iou = polygon_intersection / polygon_union
if iou > 0.5:
no_intersection = False
# update mask annotation if intersected one is bigger
if cur_poly.area > other_poly.area:
saved_annotation['segmentation'][i] = ann
elif iou > 0.05:
print('iou', iou, 'polygon1', cur_poly.area, 'polygon2', other_poly.area)
#TODO calculate intersection and union, and then IOU between polygons inside new_seg
for i in range(len(new_seg)):
other_coords = np.reshape(new_seg[i], (int(len(new_seg[i])/2), 2))
other_coords = np.int32(other_coords)
other_poly = get_largest_poly_from_self_intersection(other_coords)
polygon_intersection = cur_poly.intersection(other_poly).area
polygon_union = cur_poly.area + other_poly.area - polygon_intersection
iou = polygon_intersection / polygon_union
if iou > 0.5:
no_intersection = False
if cur_poly.area > other_poly.area:
new_seg[i] = ann
elif iou > 0.05:
print('iou', iou, 'polygon1', cur_poly.area, 'polygon2', other_poly.area)
if no_intersection:
new_seg.append(ann)
except Exception as e:
print(e)
else:
new_seg.append(ann)
annotation['segmentation'] = new_seg
if annotation['segmentation']:
annotation['id'] = next_ids['annotation']
annotation['image_id'] = image['id']
next_ids['annotation'] += 1
annotation['category_id'] = 1
json_data['annotations'][annotation['id']] = annotation
image_samples[image['id']]['annotation_ids'].append(annotation['id'])
# if print_ann:
# print(annotation)
if parkingSpots:
for spot in spots_list:
new_seg = list()
ann = spot['contour']
coords = np.reshape(ann, (-1, 2))
coords = np.int32(coords) # Convert to int32 to fillPoly function
if cv2.contourArea(coords) < 20:
print('poly area', cv2.contourArea(coords), 'removed')
elif check_duplicates:
cur_poly = get_largest_poly_from_self_intersection(coords)
no_intersection = True
try:
for saved_spot_id in image_samples[image['id']]['spot_ids']:
saved_spot = json_data['parkingSpots'][saved_spot_id]
other_coords = np.reshape(saved_spot['contour'], (-1, 2))
other_coords = np.int32(other_coords)
other_poly = get_largest_poly_from_self_intersection(other_coords)
polygon_intersection = cur_poly.intersection(other_poly).area
polygon_union = cur_poly.area + other_poly.area - polygon_intersection
iou = polygon_intersection / polygon_union
if iou > 0.5:
no_intersection = False
# update mask annotation if intersected one is bigger
if cur_poly.area > other_poly.area:
saved_spot['contour'] = ann
# elif iou > 0.05:
# print('iou spot', iou, 'polygon1', cur_poly.area, 'polygon2', other_poly.area)
#TODO calculate intersection and union, and tne IOU between polygons inside new_seg
for i in range(len(new_seg)):
other_coords = np.reshape(new_seg[i], (int(len(new_seg[i])/2), 2))
other_coords = np.int32(other_coords)
other_poly = get_largest_poly_from_self_intersection(other_coords)
polygon_intersection = cur_poly.intersection(other_poly).area
polygon_union = cur_poly.area + other_poly.area - polygon_intersection
iou = polygon_intersection / polygon_union
if iou > 0.5:
no_intersection = False
if cur_poly.area > other_poly.area:
new_seg[i] = ann
# elif iou > 0.05:
# print('iou spot', iou, 'polygon1', cur_poly.area, 'polygon2', other_poly.area)
if no_intersection:
new_seg.append(ann)
except Exception as e:
print(e)
else:
new_seg.append(ann)
spot['contour'] = new_seg
if spot['contour']:
spot['id'] = next_ids['spot']
spot['image_id'] = image['id']
next_ids['spot'] += 1
annotation['category_id'] = 1
json_data['parkingSpots'][spot['id']] = spot
image_samples[image['id']]['spot_ids'].append(spot['id'])
json_data['images'][image['file_name']] = image
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='JSON Merger',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--input', '-i', type=str)
parser.add_argument('--addition', '-a', type=str, default=None)
parser.add_argument('--output', '-o', type=str)
parser.add_argument('--dataset', '-d', type=str)
parser.add_argument('--dataset_folder', '-df', type=str)
parser.add_argument('--subset', '-s', type=str)
parser.add_argument('--check_duplicates', '-cd', dest='check_duplicates', action='store_true')
parser.set_defaults(check_duplicates=False)
parser.add_argument('--add_absent_images', '-aai', dest='add_absent_images', action='store_true')
parser.set_defaults(add_absent_images=False)
parser.add_argument('--rectangle', '-r', nargs='+', type=int, default=None)
main(parser.parse_args()) |