import json
import os
# 클래스 순서에 맞게 class_map 설정
class_map = {
"big robot": 0, # big robot을 0으로 설정
"small robot": 1 # small robot을 1로 설정
}
def convert_labelme_to_yolo(json_path, output_txt_path):
"""LabelMe JSON을 YOLO TXT 형식으로 변환"""
with open(json_path, "r", encoding="utf-8") as f:
data = json.load(f)
image_width = data["imageWidth"]
image_height = data["imageHeight"]
yolo_lines = []
for shape in data["shapes"]:
label = shape["label"]
points = shape["points"]
# YOLO는 바운딩 박스 좌표를 정규화된 (x_center, y_center, width, height)로 변환
x_min, y_min = points[0]
x_max, y_max = points[1]
x_center = (x_min + x_max) / 2 / image_width
y_center = (y_min + y_max) / 2 / image_height
width = (x_max - x_min) / image_width
height = (y_max - y_min) / image_height
class_id = class_map.get(label, -1) # 클래스 ID 찾기 (없으면 -1)
if class_id == -1:
print(f"'{label}' 클래스가 class_map에 없음. 무시됨.")
continue
# YOLO 형식: <class_id> <x_center> <y_center> <width> <height>
yolo_lines.append(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}")
# 변환된 YOLO 데이터 저장
with open(output_txt_path, "w", encoding="utf-8") as f:
f.write("\n".join(yolo_lines))
print(f"변환 완료: {output_txt_path}")
def main(input_dir,output_dir):
# 폴더 내 JSON 파일 변환 실행
for file in os.listdir(input_dir):
if file.endswith(".json"): # JSON 파일만 처리
json_path = os.path.join(input_dir, file)
txt_filename = os.path.splitext(file)[0] + ".txt" # 확장자를 .txt로 변경
txt_path = os.path.join(output_dir, txt_filename) # 출력 폴더에 저장
convert_labelme_to_yolo(json_path, txt_path)
if __name__ == "__main__":
# 입력 및 출력 폴더 설정
input_train_dir = "deeplearning/dataset2/trainimg/" # JSON 파일이 섞여 있는 폴더
output_train_dir = "deeplearning/yolo_dataset2/train/labels/" # YOLO TXT 파일을 저장할 폴더
# 입력 및 출력 폴더 설정
input_val_dir = "deeplearning/dataset2/valimg/" # JSON 파일이 섞여 있는 폴더
output_val_dir = "deeplearning/yolo_dataset2/val/labels/" # YOLO TXT 파일을 저장할 폴더
main(input_train_dir,output_train_dir)
main(input_val_dir,output_val_dir)
첫댓글 confusion matrix, 그래프의 의미 설명추가할것, 교재 6.5절 참고할것
추가하였습니다