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

yolo_converter.py 8.1 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
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
  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 PIL import Image
  6. from label_studio_converter import Converter
  7. from label_studio_converter.imports.label_config import generate_label_config
  8. from label_studio_converter.utils import get_json_root_type
  9. from collections import defaultdict
  10. from copy import deepcopy
  11. logger = logging.getLogger('root')
  12. class YOLOAnnotationConverter():
  13. def __init__(self, dataset_dir, classes = [], to_name='image', from_name='label', label_type='bbox'):
  14. """Instantiate YOLO Annotation Convertert
  15. """
  16. self.ann_type = "YOLO"
  17. self.dataset_dir = dataset_dir
  18. self.classes = classes
  19. self.url_col = "dagshub_download_url"
  20. self.to_name = to_name
  21. self.from_name = from_name
  22. self.label_type = label_type
  23. # build categories=>labels dict
  24. if len(self.classes) == 0:
  25. if not self._update_classes_from_file():
  26. logger.warning(
  27. 'No classes.txt file found and now classes array supplied,'
  28. 'this might result in errors due to missing classes'
  29. )
  30. categories = {i: line for i, line in enumerate(self.classes)}
  31. logger.info(f'Found {len(categories)} categories')
  32. # generate and save labeling config
  33. self.config = generate_label_config(
  34. categories,
  35. {from_name: 'RectangleLabels'},
  36. to_name,
  37. from_name
  38. )
  39. self.ls_converter = DagsConverter(self.config, self.dataset_dir, download_resources=False)
  40. def _update_classes_from_file(self):
  41. notes_file = os.path.join(self.dataset_dir, 'classes.txt')
  42. if os.path.exists(notes_file):
  43. with open(notes_file) as f:
  44. self.classes = [line.strip() for line in f.readlines()]
  45. return True
  46. return False
  47. def _create_bbox(self, line, image_width, image_height):
  48. label_id, x, y, width, height = line.split()
  49. x, y, width, height = (
  50. float(x),
  51. float(y),
  52. float(width),
  53. float(height),
  54. )
  55. item = {
  56. "id": uuid.uuid4().hex[0:10],
  57. "type": "rectanglelabels",
  58. "value": {
  59. "x": (x - width / 2) * 100,
  60. "y": (y - height / 2) * 100,
  61. "width": width * 100,
  62. "height": height * 100,
  63. "rotation": 0,
  64. "rectanglelabels": [self.classes[int(label_id)]],
  65. },
  66. "to_name": self.to_name,
  67. "from_name": self.from_name,
  68. "image_rotation": 0,
  69. "original_width": image_width,
  70. "original_height": image_height,
  71. }
  72. return item
  73. def _create_segmentation(self, line, image_width, image_height):
  74. label_id = line.split()[0]
  75. points = [[float(x[0]), float(x[1])] for x in zip(*[iter(line.split()[1:])]*2)]
  76. for i in range(len(points)):
  77. points[i][0] = points[i][0] * 100.0
  78. points[i][1] = points[i][1] * 100.0
  79. item = {
  80. "id": uuid.uuid4().hex[0:10],
  81. "type": "polygonlabels",
  82. "value": {
  83. "closed": True,
  84. "points": points,
  85. "polygonlabels": [self.classes[int(label_id)]],
  86. },
  87. "to_name": self.to_name,
  88. "from_name": self.from_name,
  89. "image_rotation": 0,
  90. "original_width": image_width,
  91. "original_height": image_height,
  92. }
  93. return item
  94. def to_de(self, row, out_type="annotations"):
  95. """Convert YOLO labeling to Label Studio JSON
  96. :param out_type: annotation type - "annotations" or "predictions"
  97. """
  98. # define coresponding label file and check existence
  99. image_path = row["path"]
  100. if not "images/" in image_path:
  101. image_path = os.path.join("images", image_path)
  102. label_path = image_path.replace(image_path.split(".")[-1], "txt")
  103. if "/images/" in label_path or label_path.startswith("images/"):
  104. label_path = label_path.replace("images/","labels/")
  105. else:
  106. label_path = os.path.join("labels", label_path)
  107. label_file = os.path.join(self.dataset_dir, label_path)
  108. image_file = os.path.join(self.dataset_dir, image_path)
  109. image_width = 0
  110. image_height = 0
  111. task = {
  112. "data": {
  113. # eg. '../../foo+you.py' -> '../../foo%2Byou.py'
  114. "image": row[self.url_col]
  115. }
  116. }
  117. if os.path.exists(label_file):
  118. task[out_type] = [
  119. {
  120. "result": [],
  121. "ground_truth": False,
  122. }
  123. ]
  124. # read image sizes
  125. if not (image_width and image_height):
  126. # default to opening file if we aren't given image dims. slow!
  127. with Image.open(os.path.join(image_file)) as im:
  128. image_width, image_height = im.size
  129. with open(label_file) as file:
  130. # convert all bounding boxes to Label Studio Results
  131. lines = file.readlines()
  132. for line in lines:
  133. if 'bbox' in self.label_type:
  134. item = self._create_bbox(line, image_width, image_height)
  135. task[out_type][0]['result'].append(item)
  136. if 'segmentation' in self.label_type:
  137. item = self._create_segmentation(line, image_width, image_height)
  138. task[out_type][0]['result'].append(item)
  139. task['is_labeled'] = True
  140. if task:
  141. return json.dumps(task).encode()
  142. def from_de(self, row):
  143. annotation_data = row["annotation"]
  144. ls_converter = DagsConverter(self.config, self.dataset_dir, download_resources=False)
  145. ls_converter.convert_to_yolo(input_data=annotation_data,
  146. output_dir=self.dataset_dir,
  147. output_label_dir=os.path.join(self.dataset_dir, "labels", *(row['path'].split("/")[:-1])),
  148. is_dir=False)
  149. # Add new classes to converter config
  150. ls_converter._get_labels()
  151. self._update_classes_from_file()
  152. class DagsConverter(Converter):
  153. def iter_from_json_file(self, json_file):
  154. """Extract annotation results from json file
  155. param json_file: path to task dict with annotations
  156. """
  157. with open(json_file) as j:
  158. data = json.load(j)
  159. if not id in data:
  160. data['id'] = 0
  161. for item in self.annotation_result_from_task(data):
  162. yield item
  163. def _get_labels(self):
  164. labels = set()
  165. categories = list()
  166. category_name_to_id = dict()
  167. for name, info in self._schema.items():
  168. labels |= set(info['labels'])
  169. attrs = info['labels_attrs']
  170. for label in attrs:
  171. # DagsHub: add handling for case where there is no category attribute but we want to use the order in the schema
  172. label_num = attrs[label].get('category') if attrs[label].get('category') else info['labels'].index(label)
  173. categories.append(
  174. {'id': label_num, 'name': label}
  175. )
  176. category_name_to_id[label] = label_num
  177. labels_to_add = set(labels) - set(list(category_name_to_id.keys()))
  178. labels_to_add = sorted(list(labels_to_add))
  179. idx = 0
  180. while idx in list(category_name_to_id.values()):
  181. idx += 1
  182. for label in labels_to_add:
  183. categories.append({'id': idx, 'name': label})
  184. category_name_to_id[label] = idx
  185. idx += 1
  186. while idx in list(category_name_to_id.values()):
  187. idx += 1
  188. return categories, category_name_to_id
Tip!

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

Comments

Loading...