2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

COCO形式(json)の物体検出アノテーションファイルを、yolo形式(txt)に変換するスニペット

Posted at

origin_x,origin_y,width,height を 正規化された center_x,center_y,width,heightに

COCOは単一のjsonファイルで、box座標は画像に対するサイズになっています。
yoloは画像一枚につき一つのtxtファイルで、box座標は0~1に正規化されています。

以下を実行すると、COCO形式のjsonファイルのデータを、yolo形式のtxtファイルにしてyolo_txt_save_dirに保存します。

import os
import json

coco_json_path = 'coco.json'
yolo_txt_save_dir = 'yolo_txt/'

json_open = open(coco_json_path, 'r')
json_load = json.load(json_open)

annotations = json_load['annotations']
images = json_load['images']

for annotation in annotations:
  id = annotation['image_id']
  for image in images:
    if image['id'] == id:
      file_name = image['file_name']
      im_w = image['width']
      im_h = image['height']
      txt_path = os.path.join(yolo_txt_save_dir, os.path.splitext(os.path.basename(file_name))[0] + '.txt')
      bbox = annotation['bbox']
      x = bbox[0]-(bbox[2]/2)
      y = bbox[1]-(bbox[3]/2)
      bbox = [float(bbox[0])/im_w,float(bbox[1])/im_h,float(bbox[2])/im_w,float(bbox[3])/im_h]
      cls = int(annotation['category_id'])
      line = (cls,*bbox)
      with open(f'{txt_path}', 'w') as f:
        f.write(('%g ' * len(line)).rstrip() % line + '\n')

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

機械学習、ARアプリ(Web/iOS)を作っています。
機械学習/AR関連の情報を発信しています。

Twitter
Medium
GitHub

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?