
본선 대회에서 주어진 데이터셋의 labeling은 COCO data format으로 구성되어 있었는데, 실시간으로 드론을 탐지하는 모델 개발을 고려하였을 때 YOLO 모델 학습을 가장 우선적으로 고려하였고 따라서 주어진 COCO format의 데이터셋 label을 YOLO format으로 변경해주어야만 했다. 우선 data format 변경에 앞서, COCO data format과 YOLO data format 두 가지 포맷의 차이를 확인해보았다.
COCO data format

YOLO data format


당연히 두 데이터 format 사이의 변환이 가능하다. COCO format -> YOLO format 변환의 경우 아래 두가지 방법을 추천한다.
import os
import json
from tqdm import tqdm
import shutil
def convert_bbox_coco2yolo(img_width, img_height, bbox):
# YOLO bounding box format: [x_center, y_center, width, height]
# (float values relative to width and height of image)
x_tl, y_tl, w, h = bbox
dw = 1.0 / img_width
dh = 1.0 / img_height
x_center = x_tl + w / 2.0
y_center = y_tl + h / 2.0
x = x_center * dw
y = y_center * dh
w = w * dw
h = h * dh
return [x, y, w, h]
def make_folders(path="output"):
if os.path.exists(path):
shutil.rmtree(path)
os.makedirs(path)
return path
def convert_coco_json_to_yolo_txt(output_path, json_file):
path = make_folders(output_path)
with open(json_file) as f:
json_data = json.load(f)
# write _darknet.labels, which holds names of all classes (one class per line)
label_file = os.path.join(output_path, "_darknet.labels")
with open(label_file, "w") as f:
for category in tqdm(json_data["categories"], desc="Categories"):
category_name = category["name"]
f.write(f"{category_name}\n")
for image in tqdm(json_data["images"], desc="Annotation txt for each iamge"):
img_id = image["id"]
img_name = image["file_name"]
img_width = image["width"]
img_height = image["height"]
anno_in_image = [anno for anno in json_data["annotations"] if anno["image_id"] == img_id]
anno_txt = os.path.join(output_path, img_name.split(".")[0] + ".txt")
with open(anno_txt, "w") as f:
for anno in anno_in_image:
category = anno["category_id"]
bbox_COCO = anno["bbox"]
x, y, w, h = convert_bbox_coco2yolo(img_width, img_height, bbox_COCO)
f.write(f"{category} {x:.6f} {y:.6f} {w:.6f} {h:.6f}\n")
#{'output 결과 저장경로', 'coco_format json파일 경로'}로 설정해주면 됩니다.
convert_coco_json_to_yolo_txt("data/yolo/labels/val", "/home/ubuntu/seadronesee/data/SeaDronesSee Object Detection v2/Uncompressed Version/annotations/instances_val.json")
convert_coco_json_to_yolo_txt("data/yolo/labels/train", "/home/ubuntu/seadronesee/data/SeaDronesSee Object Detection v2/Uncompressed Version/annotations/instances_train.json")


