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

yolo2labelstudio.py 4.9 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
  1. import argparse
  2. import datetime
  3. import glob
  4. import hashlib
  5. import json
  6. import os
  7. import random
  8. import requests
  9. import string
  10. import sys
  11. from PIL import Image
  12. from requests.auth import HTTPBasicAuth
  13. def gen_ascii_string(length):
  14. return ''.join(random.SystemRandom().choice(string.ascii_letters) for _ in range(length))
  15. def gen_labelstudio_json(data, repo, commit, user_info):
  16. labelstudio = os.path.join(repo, '.labelstudio')
  17. os.makedirs(labelstudio, exist_ok=True)
  18. results = []
  19. try:
  20. img = Image.open(os.path.join(repo, data))
  21. except:
  22. print(f"WARNING: Invalid image '{data}'")
  23. return
  24. label = data.replace("images", "labels")
  25. label = os.path.splitext(label)[0] + '.txt'
  26. label_fullpath = os.path.join(repo, label)
  27. if not os.path.exists(label_fullpath):
  28. return
  29. with open(label_fullpath) as f:
  30. lines = f.read().split('\n')[:-1]
  31. timestamp = datetime.datetime.utcnow().isoformat() + 'Z'
  32. for line in lines:
  33. _, cx, cy, w, h = [float(p) for p in line.split()]
  34. result = {}
  35. result["id"] = gen_ascii_string(10)
  36. result["type"] = "rectanglelabels"
  37. result["value"] = {}
  38. result["value"]["x"] = 100.0 * (cx - (w / 2))
  39. result["value"]["y"] = 100.0 * (cy - (h / 2))
  40. result["value"]["width"] = 100.0 * w
  41. result["value"]["height"] = 100.0 * h
  42. result["value"]["rotation"] = 0
  43. result["value"]["rectanglelabels"] = ["squirrel"]
  44. result["origin"] = "manual"
  45. result["to_name"] = "image"
  46. result["from_name"] = "label"
  47. result["image_rotation"] = 0
  48. result["original_width"] = img.size[0]
  49. result["original_height"] = img.size[1]
  50. results.append(result)
  51. name = user_info.get('full_name', '').split()
  52. if len(name) > 1:
  53. first_name = name[0]
  54. last_name = name[-1]
  55. elif len(name) > 0:
  56. first_name = name[0]
  57. last_name = ''
  58. else:
  59. first_name = ''
  60. last_name = ''
  61. annotation = {}
  62. annotation['completed_by'] = {}
  63. annotation['completed_by']['username'] = user_info.get('username', '')
  64. annotation['completed_by']['first_name'] = first_name
  65. annotation['completed_by']['last_name'] = last_name
  66. annotation['completed_by']['avatar'] = user_info.get('avatar_url', '')
  67. annotation['result'] = results
  68. annotation['was_cancelled'] = False
  69. annotation['ground_truth'] = False
  70. annotation['created_at'] = timestamp
  71. annotation['updated_at'] = timestamp
  72. annotation['lead_time'] = 42.0
  73. annotation['prediction'] = {}
  74. annotation['parent_prediction'] = None
  75. annotation['parent_annotation'] = None
  76. ls_json = {}
  77. ls_json['annotations'] = [annotation]
  78. ls_json['drafts'] = []
  79. ls_json['predictions'] = []
  80. ls_json['data'] = {}
  81. ls_json['data']['image'] = f'repo://{commit}/{data}'
  82. ls_json['meta'] = {}
  83. json_file = hashlib.sha1(data.encode("utf-8")).hexdigest() + '.json'
  84. json_file = os.path.join(labelstudio, json_file)
  85. with open(json_file, mode='w') as f:
  86. json.dump(ls_json, f)
  87. def is_image(filename):
  88. _, ext = os.path.splitext(filename)
  89. return ext.lower() in ('.jpg', '.jpeg', '.png')
  90. def get_user_info(user, token):
  91. url = f'https://dagshub.com/api/v1/users/{user}'
  92. auth = HTTPBasicAuth(user, token)
  93. res = requests.get(url, auth=auth)
  94. try:
  95. info = json.loads(res.content)
  96. return info
  97. except:
  98. print(f'WARNING: Invalid JSON received from server when looking up {user}')
  99. print(res.content)
  100. return {}
  101. def main():
  102. parser = argparse.ArgumentParser('Create LabelStudio compatible annoations from a YOLO-style dataset, within a repo')
  103. parser.add_argument('--repo', required=True, help='Path to the repo')
  104. parser.add_argument('--data', required=True, help='Path to folder or single image within the repo to convert')
  105. parser.add_argument('--commit', required=True, help='Hash of a commit for which the data exist(s)')
  106. parser.add_argument('--user', required='--token' in sys.argv, help='Username for the labeler')
  107. parser.add_argument('--token', required=False, help='Token for the user, to grab info about the labeler')
  108. args = parser.parse_args()
  109. user_info = {}
  110. if args.token is not None:
  111. user_info = get_user_info(args.user, args.token)
  112. elif args.user is not None:
  113. user_info['username'] = args.user
  114. if args.data.startswith(args.repo):
  115. data = args.data[len(args.repo):]
  116. if data.startswith('/'):
  117. data = data[1:]
  118. else:
  119. data = args.data
  120. data_fullpath = os.path.join(args.repo, data)
  121. if os.path.isdir(data_fullpath):
  122. data = [os.path.join(data, l) for l in os.listdir(data_fullpath) if is_image(l)]
  123. else:
  124. data = [data]
  125. for d in data:
  126. gen_labelstudio_json(d, args.repo, args.commit, user_info)
  127. if __name__ == '__main__':
  128. main()
Tip!

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

Comments

Loading...