Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

coco_converter.py 6.5 KB

You have to be logged in to leave a comment. Sign In
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
  1. import os
  2. import json # better to use "imports ujson as json" for the best performance
  3. import uuid
  4. import logging
  5. from label_studio_converter.imports.label_config import generate_label_config
  6. from .dags_converter import DagsConverter
  7. logger = logging.getLogger('root')
  8. class COCOAnnotationConverter():
  9. def __init__(self, annotation_file, to_name='image', from_name='label', label_type='bbox'):
  10. """Instantiate COCO Annotation Converter
  11. """
  12. self.ann_type = "COCO"
  13. self.annotation_file = annotation_file
  14. self.url_col = "dagshub_download_url"
  15. self.to_name = to_name
  16. self.from_name = from_name
  17. self.label_type = label_type
  18. # build categories=>labels dict
  19. if not self._update_data_from_file():
  20. raise ImportError(f'Unable to import annotations from {self.annotation_file}')
  21. categories = {i: line for i, line in enumerate(self.classes)}
  22. logger.info(f'Found {len(categories)} categories')
  23. if label_type == 'bbox':
  24. tags = {from_name: 'RectangleLabels'}
  25. elif label_type == 'segmentation':
  26. tags = {from_name: 'PolygonLabels'}
  27. else:
  28. raise NotImplementedError(f'Label type ({label_type}) has not been implemented.')
  29. # generate and save labeling config
  30. self.config = generate_label_config(
  31. categories,
  32. tags,
  33. to_name,
  34. from_name
  35. )
  36. def _update_data_from_file(self):
  37. if os.path.exists(self.annotation_file):
  38. with open(self.annotation_file) as f:
  39. data = json.load(f)
  40. self.class_map = {c['id']: c['name'] for c in data['categories']}
  41. self.classes = [c['name'] for c in data['categories']]
  42. self.images = {i['file_name']: {'height': i['height'], 'width': i['width'], 'id': i['id']} for i in data['images']}
  43. self.annotations = {}
  44. for ann in data['annotations']:
  45. image_id = ann['image_id']
  46. self.annotations[image_id] = self.annotations.get(image_id, []) + [ann]
  47. return True
  48. return False
  49. def _create_bbox(self, image_info, annotation_info):
  50. if image_info['id'] != annotation_info['image_id']:
  51. raise ValueError(f'Image ID ({image_info["id"]}) does not match Annotation Image ID ({annotation_info["image_id"]})')
  52. label_id = annotation_info['category_id']
  53. image_width = image_info['width']
  54. image_height = image_info['height']
  55. x, y, width, height = annotation_info['bbox']
  56. x, y, width, height = (
  57. float(x),
  58. float(y),
  59. float(width),
  60. float(height),
  61. )
  62. item = {
  63. "id": uuid.uuid4().hex[0:10],
  64. "type": "rectanglelabels",
  65. "value": {
  66. "x": (x / image_width) * 100,
  67. "y": (y / image_height) * 100,
  68. "width": (width / image_width) * 100,
  69. "height": (height / image_height) * 100,
  70. "rotation": 0,
  71. "rectanglelabels": [self.classes[int(label_id)]],
  72. },
  73. "to_name": self.to_name,
  74. "from_name": self.from_name,
  75. "image_rotation": 0,
  76. "original_width": image_width,
  77. "original_height": image_height,
  78. }
  79. return item
  80. def _create_segmentation(self, image_info, annotation_info):
  81. if image_info['id'] != annotation_info['image_id']:
  82. raise ValueError(f'Image ID ({image_info["id"]}) does not match Annotation Image ID ({annotation_info["image_id"]})')
  83. label_id = annotation_info['category_id']
  84. image_width = image_info['width']
  85. image_height = image_info['height']
  86. segmentation = annotation_info['segmentation'][0]
  87. points = zip(segmentation[::2], segmentation[1::2])
  88. points = [[100.0 * float(x) / image_width, 100.0 * float(y) / image_height] for x, y in points]
  89. item = {
  90. "id": uuid.uuid4().hex[0:10],
  91. "type": "polygonlabels",
  92. "value": {
  93. "closed": True,
  94. "points": points,
  95. "polygonlabels": [self.class_map[label_id]],
  96. },
  97. "to_name": self.to_name,
  98. "from_name": self.from_name,
  99. "image_rotation": 0,
  100. "original_width": image_width,
  101. "original_height": image_height,
  102. }
  103. return item
  104. def to_de(self, row, out_type="annotations"):
  105. """Convert COCO labeling to Label Studio JSON
  106. :param out_type: annotation type - "annotations" or "predictions"
  107. """
  108. # define coresponding label file and check existence
  109. image_path = row["path"]
  110. image_info = self.images.get(image_path, None) or self.images.get(os.path.split(image_path)[-1], None)
  111. task = None
  112. if image_info is not None:
  113. task = {
  114. "data": {
  115. # eg. '../../foo+you.py' -> '../../foo%2Byou.py'
  116. "image": row[self.url_col]
  117. }
  118. }
  119. image_width = image_info['width']
  120. image_height = image_info['height']
  121. task[out_type] = [
  122. {
  123. "result": [],
  124. "ground_truth": False,
  125. }
  126. ]
  127. # convert all bounding boxes to Label Studio Results
  128. for annotation in self.annotations.get(image_info['id'], []):
  129. if 'bbox' in self.label_type:
  130. item = self._create_bbox(image_info, annotation)
  131. task[out_type][0]['result'].append(item)
  132. if 'segmentation' in self.label_type:
  133. item = self._create_segmentation(image_info, annotation)
  134. task[out_type][0]['result'].append(item)
  135. task['is_labeled'] = True
  136. if task:
  137. return json.dumps(task).encode()
  138. def from_de(self, row):
  139. annotation_data = row["annotation"]
  140. ls_converter = DagsConverter(self.config, self.dataset_dir, download_resources=False)
  141. output_dir = os.path.split(self.annotation_file)[0]
  142. ls_converter.convert_to_coco(input_data=annotation_data,
  143. output_dir=output_dir,
  144. output_image_dir=os.path.join(output_dir, 'data'),
  145. is_dir=False)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...