1. 程式人生 > 其它 >YOLO格式標註資料轉COCO標註資料

YOLO格式標註資料轉COCO標註資料

技術標籤:目標檢測YOLOCOCO 標註

這裡僅僅考慮person類別,如果考慮其他類別,則需要增加類別資訊,稍作調整即可。

import json
import os
import imagesize
import copy


def txt_to_json(img_dir,annotation_dir,json_path,img_format='.jpg',annotation_format='.txt'):
    # json 檔案主要兩項內容
    json_dict = dict()
    annotations = list()
    images = list(
) categories = list() # 一個標籤和一張圖 one_annotation = dict() one_image = dict() annotation_bbox_id = 0 for file in os.listdir(annotation_dir): if file.endswith(annotation_format): # 讀取圖片資訊:長寬,整合到one_image當中 one_image['file_name'] = file.split('.')[0]
+img_format one_image['id'] = file.split('.')[0] one_image['width'],one_image['height'] = imagesize.get(os.path.join(img_dir,one_image['file_name'])) # 讀取txt檔案的內容,for迴圈整合到one_annotation當中 with open(os.path.join(annotation_dir,file), 'r') as f: for
line in f.readlines(): line = line.strip('\n') # 去掉每一行中的換行符 [categories_id,x,y,w,h] = line.split(' ') w = one_image['width']*float(w) h = one_image['height']*float(h) x_min = one_image['width']*float(x) - w/2.0 y_min = one_image['height']*float(y) - h/2.0 one_annotation['segmentation'] = [] one_annotation['area'] = w*h one_annotation['iscrowd'] = 0 one_annotation['image_id'] = one_image['id'] one_annotation["bbox"] = [x_min,y_min,w,h] one_annotation["category_id"] = 1 one_annotation["id"] = annotation_bbox_id # 這裡的id就是一個編號,每一個人的編號都不相同 annotation_bbox_id = annotation_bbox_id + 1 annotations.append(copy.deepcopy(one_annotation)) images.append(copy.deepcopy(one_image)) category = dict() category['supercategory'] = 'person' category['person'] = 'person' category['id'] = 1 categories.append(category) json_dict['annotations'] = annotations json_dict['images'] = images json_dict['categories'] = categories # 將獲取的xml內容寫入到json檔案中 with open(json_path, 'w') as f: f.write(json.dumps(json_dict, indent=1, separators=(',', ':'))) if __name__ == '__main__': img_dir = './train/' annotation_dir = './train/' json_path = './annotations/train.json' txt_to_json(img_dir,annotation_dir,json_path)