22Module for converting labelbox.com JSON exports to MS COCO format.
33"""
44
5- import json
65import datetime as dt
6+ import json
77import logging
8+ from PIL import Image
9+ import requests
810from shapely import wkt
911from shapely .geometry import Polygon
10- import requests
11- from PIL import Image
12+ from typing import Any , Dict , Sequence
1213
1314from labelbox .exceptions import UnknownFormatError
1415
@@ -25,15 +26,7 @@ def from_json(labeled_data, coco_output, label_format='WKT'):
2526 for data in label_data :
2627 # Download and get image name
2728 try :
28- image = {
29- "id" : data ['ID' ],
30- "file_name" : data ['Labeled Data' ],
31- "license" : None ,
32- "flickr_url" : data ['Labeled Data' ],
33- "coco_url" : data ['Labeled Data' ],
34- "date_captured" : None ,
35- }
36- _add_label (coco , image , data ['Label' ], label_format )
29+ add_label (coco , data ['ID' ], data ['Labeled Data' ], data ['Label' ], label_format )
3730 except requests .exceptions .MissingSchema as exc :
3831 logging .exception (exc )
3932 continue
@@ -45,8 +38,16 @@ def from_json(labeled_data, coco_output, label_format='WKT'):
4538 file_handle .write (json .dumps (coco ))
4639
4740
48- def make_coco_metadata (project_name , created_by ):
49- "Initializes COCO export data structure."
41+ def make_coco_metadata (project_name : str , created_by : str ) -> Dict [str , Any ]:
42+ """Initializes COCO export data structure.
43+
44+ Args:
45+ project_name: name of the project
46+ created_by: email of the project creator
47+
48+ Returns:
49+ The COCO export represented as a dictionary.
50+ """
5051 coco = {
5152 'info' : None ,
5253 'images' : [],
@@ -67,9 +68,30 @@ def make_coco_metadata(project_name, created_by):
6768 return coco
6869
6970
70- def _add_label (coco , image , labels , label_format ):
71- "Incrementally updates COCO export data structure with a new label."
72- response = requests .get (image ['coco_url' ], stream = True )
71+ def add_label (
72+ coco : Dict [str , Any ], label_id : str , image_url : str ,
73+ labels : Sequence [Any ], label_format : str ):
74+ """Incrementally updates COCO export data structure with a new label.
75+
76+ Args:
77+ coco: The current COCO export, will be incrementally updated by this method.
78+ label_id: ID for the instance to write
79+ image_url: URL to download image file from
80+ labels: Labelbox formatted labels to use for generating annotation
81+ label_format: Format of the labeled data. Valid options are: "WKT" and "XY", default is "WKT".
82+
83+ Returns:
84+ The updated COCO export represented as a dictionary.
85+ """
86+ image = {
87+ "id" : label_id ,
88+ "file_name" : image_url ,
89+ "license" : None ,
90+ "flickr_url" : image_url ,
91+ "coco_url" : image_url ,
92+ "date_captured" : None ,
93+ }
94+ response = requests .get (image_url , stream = True )
7395 response .raw .decode_content = True
7496 image ['width' ], image ['height' ] = Image .open (response .raw ).size
7597
0 commit comments