기계는 거짓말하지 않는다

Labelme JSON data label 명 변경 본문

AI

Labelme JSON data label 명 변경

KillinTime 2022. 10. 28. 10:45

Labelme JSON data의 label 명이 잘못되었을 때 변경하고 싶은 경우

하위 디렉터리가 존재하거나 존재하지 않는다면 수정이 필요하다.

import os
import glob
import datetime
import time
import json

# 경로 변경
dir_root_path = "G:/data"
# 수정된 데이터 저장 경로
dest_dir_path = "G:/data_label_modify"
# 하위 디렉터리
sub_dir_name_list = ["dir_001", "dir_006"]

# perosn -> person, carr -> car
CHANGE_LABEL_TABLE = {
    "perosn" : "person",
    "carr" : "car"
}

read_count = 0

start_time = time.time()

for sub_dir_name in sub_dir_name_list:
    sub_dir_name = os.path.basename(sub_dir_name)
    label_path_list = glob.glob(os.path.join(dir_root_path + "/" + sub_dir_name, "*.json"))
    read_count = 0

    print(f"{sub_dir_name} label")
    
    for label_path in label_path_list:
        change_check = False
        
        with open(label_path, 'r', encoding='utf-8-sig') as f:
            data = json.load(f)
            for i, shapes_data in enumerate(data["shapes"]):
                if shapes_data["label"] in CHANGE_LABEL_TABLE:
                    shapes_data["label"] = CHANGE_LABEL_TABLE[shapes_data["label"]]
                    data["shapes"][i] = shapes_data
                    
                    change_check = True
                    
        if change_check == True:
            print(label_path)
            if not os.path.exists(dest_dir_path + "/" + sub_dir_name):
                os.makedirs(dest_dir_path + "/" + sub_dir_name)
            
            with open(dest_dir_path + "/" + sub_dir_name + "/" + os.path.basename(label_path), "w") as f:
                json.dump(data, f, indent=2)
                        
                        
        read_count += 1
        
        if read_count % 1000 == 0:
            print(f"{read_count} / {len(label_path_list)}")
            
print(f"Total Time: {datetime.timedelta(seconds=int(time.time() - start_time))}")

 

'AI' 카테고리의 다른 글

torch load_state_dict model key 변경  (0) 2023.02.03
Darknet make libdarknet.so  (0) 2022.11.04
Labelme JSON data label 별 object 개수  (0) 2022.10.28
YOLO label 텍스트 object 개수  (2) 2022.10.23
YOLO label 텍스트 classid 제외  (1) 2022.10.23
Comments