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 6.4 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
  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.imports.label_config import generate_label_config
  7. from .dags_converter import DagsConverter
  8. logger = logging.getLogger('root')
  9. class YOLOAnnotationConverter():
  10. def __init__(self, dataset_dir, classes = [], to_name='image', from_name='label', label_type='bbox'):
  11. """Instantiate YOLO Annotation Convertert
  12. """
  13. self.ann_type = "YOLO"
  14. self.dataset_dir = dataset_dir
  15. self.classes = classes
  16. self.url_col = "dagshub_download_url"
  17. self.to_name = to_name
  18. self.from_name = from_name
  19. self.label_type = label_type
  20. # build categories=>labels dict
  21. if len(self.classes) == 0:
  22. if not self._update_classes_from_file():
  23. logger.warning(
  24. 'No classes.txt file found and now classes array supplied,'
  25. 'this might result in errors due to missing classes'
  26. )
  27. categories = {i: line for i, line in enumerate(self.classes)}
  28. logger.info(f'Found {len(categories)} categories')
  29. # generate and save labeling config
  30. self.config = generate_label_config(
  31. categories,
  32. {from_name: 'RectangleLabels'},
  33. to_name,
  34. from_name
  35. )
  36. self.ls_converter = DagsConverter(self.config, self.dataset_dir, download_resources=False)
  37. def _update_classes_from_file(self):
  38. notes_file = os.path.join(self.dataset_dir, 'classes.txt')
  39. if os.path.exists(notes_file):
  40. with open(notes_file) as f:
  41. self.classes = [line.strip() for line in f.readlines()]
  42. return True
  43. return False
  44. def _create_bbox(self, line, image_width, image_height):
  45. label_id, x, y, width, height = line.split()
  46. x, y, width, height = (
  47. float(x),
  48. float(y),
  49. float(width),
  50. float(height),
  51. )
  52. item = {
  53. "id": uuid.uuid4().hex[0:10],
  54. "type": "rectanglelabels",
  55. "value": {
  56. "x": (x - width / 2) * 100,
  57. "y": (y - height / 2) * 100,
  58. "width": width * 100,
  59. "height": height * 100,
  60. "rotation": 0,
  61. "rectanglelabels": [self.classes[int(label_id)]],
  62. },
  63. "to_name": self.to_name,
  64. "from_name": self.from_name,
  65. "image_rotation": 0,
  66. "original_width": image_width,
  67. "original_height": image_height,
  68. }
  69. return item
  70. def _create_segmentation(self, line, image_width, image_height):
  71. label_id = line.split()[0]
  72. points = [[float(x[0]), float(x[1])] for x in zip(*[iter(line.split()[1:])]*2)]
  73. for i in range(len(points)):
  74. points[i][0] = points[i][0] * 100.0
  75. points[i][1] = points[i][1] * 100.0
  76. item = {
  77. "id": uuid.uuid4().hex[0:10],
  78. "type": "polygonlabels",
  79. "value": {
  80. "closed": True,
  81. "points": points,
  82. "polygonlabels": [self.classes[int(label_id)]],
  83. },
  84. "to_name": self.to_name,
  85. "from_name": self.from_name,
  86. "image_rotation": 0,
  87. "original_width": image_width,
  88. "original_height": image_height,
  89. }
  90. return item
  91. def to_de(self, row, out_type="annotations"):
  92. """Convert YOLO labeling to Label Studio JSON
  93. :param out_type: annotation type - "annotations" or "predictions"
  94. """
  95. # define coresponding label file and check existence
  96. image_path = row["path"]
  97. if not "images/" in image_path:
  98. image_path = os.path.join("images", image_path)
  99. label_path = image_path.replace(image_path.split(".")[-1], "txt")
  100. if "/images/" in label_path or label_path.startswith("images/"):
  101. label_path = label_path.replace("images/","labels/")
  102. else:
  103. label_path = os.path.join("labels", label_path)
  104. label_file = os.path.join(self.dataset_dir, label_path)
  105. image_file = os.path.join(self.dataset_dir, image_path)
  106. image_width = 0
  107. image_height = 0
  108. task = None
  109. if os.path.exists(label_file):
  110. task = {
  111. "data": {
  112. # eg. '../../foo+you.py' -> '../../foo%2Byou.py'
  113. "image": row[self.url_col]
  114. }
  115. }
  116. task[out_type] = [
  117. {
  118. "result": [],
  119. "ground_truth": False,
  120. }
  121. ]
  122. # read image sizes
  123. if not (image_width and image_height):
  124. # default to opening file if we aren't given image dims. slow!
  125. with Image.open(os.path.join(image_file)) as im:
  126. image_width, image_height = im.size
  127. with open(label_file) as file:
  128. # convert all bounding boxes to Label Studio Results
  129. lines = file.readlines()
  130. for line in lines:
  131. if 'bbox' in self.label_type:
  132. item = self._create_bbox(line, image_width, image_height)
  133. task[out_type][0]['result'].append(item)
  134. if 'segmentation' in self.label_type:
  135. item = self._create_segmentation(line, image_width, image_height)
  136. task[out_type][0]['result'].append(item)
  137. task['is_labeled'] = True
  138. if task:
  139. return json.dumps(task).encode()
  140. def from_de(self, row):
  141. annotation_data = row["annotation"]
  142. ls_converter = DagsConverter(self.config, self.dataset_dir, download_resources=False)
  143. ls_converter.convert_to_yolo(input_data=annotation_data,
  144. output_dir=self.dataset_dir,
  145. output_label_dir=os.path.join(self.dataset_dir, "labels", row['split'], *(row['path'].split("/")[:-1])),
  146. is_dir=False)
  147. # Add new classes to converter config
  148. ls_converter._get_labels()
  149. self._update_classes_from_file()
Tip!

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

Comments

Loading...