def convert_to_base_format(self) -> list[Image]: def load_bounding_boxes(boxes: list) -> list[Annotation]: annotations = [] for box in boxes: values = (box['xmin'], box['ymin'], box['xmax'], box['ymax']) bbox = BoundingBox(box_values=values, box_format=BoundingBoxFormat.VOC) bbox.label = box['label'] annotations.append(bbox) return annotations images = [] for image_name in self.boxes_json: image_filename = image_name + '.jpg' img_json = self.boxes_json[image_name] img = Image(filename=image_filename, width=img_json['width'], height=img_json['height']) img.annotations = load_bounding_boxes(img_json['bbox']) images.append(img) return images
json_dict = {'images': json_images} import json from pathlib import Path # create folder path if not existent output_file = kwargs.get('outputFile') Path(output_file).parent.mkdir(parents=True, exist_ok=True) with open(file=output_file, mode='w') as file: json.dump(obj=json_dict, fp=file, indent=2) if __name__ == '__main__': img = Image(filename='1001.png', width=512, height=256) bb1 = BoundingBox((12, 256, 34, 454), BoundingBoxFormat.COCO) bb1.label = 'Polyp1' img.annotations = [ bb1, BoundingBox((9, 10, 21, 47), BoundingBoxFormat.COCO), BoundingBox((45, 6, 3, 4), BoundingBoxFormat.COCO) ] img1 = Image(filename='1020.png', width=512, height=256) bb1 = BoundingBox((142, 123, 5, 78), BoundingBoxFormat.COCO) bb1.label = 'Polyp2' img1.annotations = [ bb1, BoundingBox((75, 444, 666, 77), BoundingBoxFormat.COCO), BoundingBox((66, 2, 3, 8), BoundingBoxFormat.COCO) ] write(images=[img, img1], annotation_format=BoundingBoxFormat.VOC)
else: config_params = default_config images = load_images(args.path, **config_params) class_at_end = config_params.get('classAtEnd') box_format = config_params.get('boundingBox') image_width = config_params.get('imageWidth') image_height = config_params.get('imageHeight') keys = list(images.keys()) keys.sort(key=lambda x: int(x.split('.')[0])) image_objects = [] for k in keys: img = Image(filename=k, width=image_width, height=image_height) annotations = [] for annotation in images[k]: label = annotation[4] if class_at_end else annotation[0] box_values = annotation[0:4] if class_at_end else annotation[1:5] a = BoundingBox(box_values=box_values, box_format=BoundingBoxFormat(box_format)) a.label = label annotations.append(a) img.annotations = annotations image_objects.append(img) write(images=image_objects, annotation_format=BoundingBoxFormat.COCO, **config_params)