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())