Safemotion Lib
Loading...
Searching...
No Matches
utils_data.py
Go to the documentation of this file.
1import copy
2import json
3import os
4import platform
5import re
6
7
8from smdataset.version_info import *
9
10
11def check_json_format(path_format, json_file_name):
12 """
13 json 파일 이름이 해당 포맷에 부합하는지 확인하는 기능
14 args:
15 path_format : 확인하려는 포맷
16 json_file_name : 확인하려는 파일 이름
17 return (bool): 부합여부
18 """
19 try :
20 for pf in path_format:
21 filename_re = re.compile(pf)
22 str_format = filename_re.search(json_file_name).group()
23 except:
24 return False
25
26 return True
27
28def check_json_version(json_file_name):
29 """
30 json_file_name 이름으로 버전을 확인하는 기능
31 return (int): json 파일의 버전
32 """
33 for key, path_format in PATH_FORMAT.items():
34 if check_json_format(path_format, json_file_name):
35 return key
36 return None
37
38def join(path_list):
39 """
40 os.path.join 기능 커스텀, 플랫폼에 따라 다르게 동작함
41 args:
42 path_list (list): 이어붙이려는 폴더 및 경로 리스트
43 return (str) : path_list를 결합한 경로
44 """
45 if platform.system().lower() == 'windows':
46 return "/".join(path_list)
47 else:
48 path_list_tmp = [path_list[0]]
49 for p in path_list[1:]:
50 p_list = p.split('/')
51 if '' in p_list:
52 p_list.remove('')
53 path_list_tmp.extend(p_list)
54 return os.path.join(*path_list_tmp)
55
56def make_dataset_folder_path(json_file_name, ret_img_folder=False, json_version=None):
57 """
58 json파일 이름으로 json 파일이 저장된 폴더와 이미지 폴더를 만드는 기능
59 args:
60 json_file_name (str): json 파일 이름
61 ret_img_folder (bool): 이미지 폴더 반환 여부
62 json_version (bool): json 파일 버전, 설정하지 않으면 json 파일 이름으로 json 파일 버전을 확인함
63 return (str): json 파일이 저장된 폴더경로, 이미지 경로
64 """
65 if json_version is None:
66 json_version = check_json_version(json_file_name)
67
68 path_format = PATH_FORMAT[json_version]
69 dataset_path_list = []
70 for pf in path_format:
71 filename_re = re.compile(pf)
72 str_format = filename_re.search(json_file_name).group()
73 dataset_path_list.append(str_format)
74
75 json_path_list = dataset_path_list[:2]
76 json_folder = join(json_path_list)
77 image_folder = join(dataset_path_list)
78
79
80 if ret_img_folder:
81 return json_folder, image_folder
82 else:
83 return json_folder
84
85def make_image_base_path(json_version, anno_path):
86 """
87 데이터셋이 저장된 기본 경로를 생성하는 기능
88 ver 11
89 json 파일 저장 경로 : base_path/annotation/P/C/json_name
90 이미지 파일 저장 경로 : base_path/images/P/C/A/R/img_name
91 args:
92 json_version (int): json 파일 버전
93 anno_path (str): json 파일 경로
94 return:
95 base_path : 데이터(json, 이미지)가 저장된 폴더
96 image_base_path : 이미지가 저장된 기본 경로(base_path/images)
97 """
98 split_dataset = anno_path.split("/")
99 json_file_name = split_dataset[-1]
100 if json_version == 10:
101 base_path_list = split_dataset[:-3]
102 image_base_path_list = copy.deepcopy(base_path_list)
103 elif json_version == 11:
104 base_path_list = split_dataset[:-4]
105 image_base_path_list = copy.deepcopy(base_path_list)
106 image_base_path_list.append('images')
107
108 path_format = PATH_FORMAT[json_version]
109 for pf in path_format:
110 filename_re = re.compile(pf)
111 str_format = filename_re.search(json_file_name).group()
112 image_base_path_list.append(str_format)
113
114 if platform.system().lower() == 'windows':
115 image_base_path = "/".join(image_base_path_list)
116 base_path = "/".join(base_path_list)
117 else:
118 image_base_path = os.path.join("/", *image_base_path_list)
119 base_path = os.path.join("/", *base_path_list)
120
121 return base_path, image_base_path
122
123def make_image_folder(json_version, anno_path):
124 """
125 어노테이션 파일에 대응하는 이미지가 저장된 경로를 생성하는 기능
126 image_base_path 뒤에 붙는 폴더
127 args:
128 json_version (int): json 파일 버전
129 anno_path (str): json 파일 경로
130 return:
131 image_folder_path : 이미지가 저장된 폴더
132 """
133 split_dataset = anno_path.split("/")
134 json_file_name = split_dataset[-1]
135
136 image_folder_path_list = []
137 path_format = PATH_FORMAT[json_version]
138 for pf in path_format:
139 filename_re = re.compile(pf)
140 str_format = filename_re.search(json_file_name).group()
141 image_folder_path_list.append(str_format)
142
143 if platform.system().lower() == 'windows':
144 image_folder_path = "/".join(image_folder_path_list)
145 else:
146 image_folder_path = os.path.join(*image_folder_path_list)
147
148 return image_folder_path
149
150
151def load_annotation(anno_path):
152 """
153 어노테이션 파일을 로드해서 기본 정보를 반환하는 기능
154 args:
155 anno_path (str): json 파일 경로
156 return:
157 json_version (int): json 파일 버전
158 label_map_version (int): 레이블맵 버전
159 base_path (str): 데이터가 저장된 기본 경로
160 image_base_path (str): 이미지가 저장된 기본 경로
161 dataset (dict): 어노테이션 데이터
162 """
163 with open(anno_path, "r") as json_file:
164 dataset = json.load(json_file)
165
166 json_version = int(float(dataset["info"]["version"])*10)
167 label_map_version = int(float(dataset["info"]["label_map_version"])*10)
168 base_path, image_base_path = make_image_base_path(json_version, anno_path)
169 dataset = check_and_init_dataset(dataset, CHECK_LIST[json_version]["keys"], CHECK_LIST[json_version]["default_value"])
170
171 return json_version, label_map_version, base_path, image_base_path, dataset
172
173def save_json(path, dataset):
174 """
175 어노테이션 데이터를 저장하는 기능
176 args:
177 path (str): 저장 경로
178 dataset (dict): 저장하는 데이터
179 """
180 try:
181 with open(path, "w") as json_file:
182 json.dump(dataset, json_file)
183 except Exception as e:
184 print(e)
185
186def load_json(path):
187 """
188 어노테이션 데이터를 로드하는 기능
189 args:
190 path (str): 어노테이션 경로
191 return (dict): 어노테이션 데이터
192 """
193 try:
194 with open(path, "r") as json_file:
195 data = json.load(json_file)
196 except Exception as e:
197 data = None
198
199 return data
200
201def check_and_init_dataset(dataset, check_list, default_value):
202 """
203 어노테이션 데이터를 확인해서 필요한 정보를 초기화 하는 기능
204 args:
205 dataset (dict): 어노테이션 데이터
206 check_list (list[str]): 확인하는 정보, 어노테이션 데이터에 해당 키가 없으면 default_value로 초기화 시켜줌
207 default_value : 초기화 값
208 return (dict): 어노테이션 데이터
209 """
210 for idx, anno in enumerate(dataset['annotations']):
211 for check_key, init_val in zip(check_list, default_value):
212 if not (check_key in anno):
213 dataset['annotations'][idx][check_key] = init_val
214 return dataset
215
216def check_and_init_dictionary(dictionary, check_list, default_value):
217 """
218 데이터를 확인해서 필요한 정보를 초기화 하는 기능
219 args:
220 dictionary (dict): 데이터
221 check_list (list[str]): 확인하는 정보, 데이터에 해당 키가 없으면 default_value로 초기화 시켜줌
222 default_value : 초기화 값
223 return (dict): 데이터
224 """
225 for key, val in zip(check_list, default_value):
226 if not key in dictionary:
227 dictionary[key] = val
228 return dictionary
229
230def make_dummy_annotation(anno_id, image_id, track_id=0):
231 """
232 더미데이터를 생성하는 기능
233 args:
234 anno_id (int): 어노테이션 아이디
235 image_id (int): 이미지 아이디
236 track_id (int): 추적 아이디
237 return (dict): 더미 데이터
238 """
239 tmp_annotation = {
240 "id": anno_id,
241 "image_id": image_id,
242 "category_id": 1,
243 "iscrowd": 0,
244 "keypoints": [
245 [178.87325418994442, 168.6456005586591, 1.0],
246 [197.7807262569836, 135.67562849162016, 1.0],
247 [149.12639664804487, 140.08938547486025, 1.0],
248 [241.84322625698292, 161.00872905027938, 1.0],
249 [121.84322625698292, 161.00872905027938, 1.0],
250 [218.3100558659221, 205.59811452513907, 1.0],
251 [151.26187150837973, 209.51885474860308, 1.0],
252 [274.60125698323964, 257.7213687150835, 1.0],
253 [112.21508379888269, 268.0677374301673, 1.0],
254 [320.4018854748606, 337.25139664804476, 1.0],
255 [87.6002094972066, 346.36592178770945, 1.0],
256 [246.41445530726241, 379.5006983240222, 1.0],
257 [175.2807262569836, 380.26012569832403, 1.0],
258 [283.3463687150843, 503.20949720670353, 1.0],
259 [168.83449720670387, 514.8495111731842, 1.0],
260 [316.25453910614533, 637.7988826815641, 1.0],
261 [157.21508379888246, 641.4738128491614, 1.0],
262 ],
263 "area": 903482.25,
264 "bbox": [32.3882681564246, 17.625698324022324, 391.0, 710.0],
265 "ageclass": 0,
266 "genderclass": 0,
267 "upperclass": 0,
268 "uppercolor": [255.0, 255.0, 255.0],
269 "lowerclass": 0,
270 "lowercolor": [255.0, 255.0, 255.0],
271 "hatvisible": 0,
272 "hatcolor": [-1.0, -1.0, -1.0],
273 "bagvisible": 0,
274 "bagcolor": [-1.0, -1.0, -1.0],
275 "action_id": {'action': 0, 'pose':0, 'hand':0, 'foot':0},
276 "mutual_action": 0,
277 "mutual_action_target": [],
278 "abnormal_id": 0,
279 "dangerzone": [0, 0, 0, 0, 0, 0, 0, 0],
280 "track_id": track_id,
281 "ismodify": 0,
282 }
283 return tmp_annotation
284
285def load_scenario(json_version, scenario_num):
286 path = os.path.join(SCENARIO_FILE_BASE, SCENARIO_FILE[json_version])
287 with open(path, "r", encoding="UTF8") as file:
288 lines = file.readlines()
289 lines = [line.rstrip() for line in lines]
290
291 sceneLine = []
292 for i in lines:
293 tmp_i = i.split(".")
294 if tmp_i[0] == scenario_num:
295 sceneLine.append(tmp_i[1])
296 return sceneLine
297
298def load_label_map(label_map_ver, label_key):
299 file_name = LABEL_FILE_INFO[label_map_ver][label_key]['file_name']
300 splitStr = LABEL_FILE_INFO[label_map_ver][label_key]['keys']
301 path = os.path.join(LABEL_BASE, file_name)
302
303 labels = dict.fromkeys(splitStr)
304 with open(path, "r", encoding='UTF-8') as txt_file:
305 lines = txt_file.readlines()
306
307 key = splitStr[0]
308
309 for line in lines:
310 line = line.strip()
311 if len(line) < 1:
312 continue
313
314 if line in splitStr:
315 key = line
316 labels[key] = []
317 continue
318
319 labels[key].append(line)
320
321 return labels, splitStr
322
323
324def search_json_by_path_format(folder, data_root = None):
325 if data_root is None:
326 data_root = folder
327
328 fileEx = '.json'
329
330 json_list = []
331 for path, dirs, files in os.walk(folder):
332 if path.split('/')[-1].startswith('.'):
333 continue
334 json_list.extend([ file for file in files if file.endswith(fileEx)])
335
336 json_list.sort()
337
338 json_path = []
339 for file in json_list:
340 json_path.append(join( [data_root, make_dataset_folder_path(file), file] ))
341
342 return json_list, json_path
check_and_init_dataset(dataset, check_list, default_value)
make_dataset_folder_path(json_file_name, ret_img_folder=False, json_version=None)
Definition utils_data.py:56
search_json_by_path_format(folder, data_root=None)
make_image_folder(json_version, anno_path)
save_json(path, dataset)
check_and_init_dictionary(dictionary, check_list, default_value)
check_json_format(path_format, json_file_name)
Definition utils_data.py:11
check_json_version(json_file_name)
Definition utils_data.py:28
load_annotation(anno_path)
load_label_map(label_map_ver, label_key)
join(path_list)
Definition utils_data.py:38
load_scenario(json_version, scenario_num)
make_image_base_path(json_version, anno_path)
Definition utils_data.py:85
load_json(path)
make_dummy_annotation(anno_id, image_id, track_id=0)