COCO json annotation to YOLO txt format
Asked Answered
D

5

9

enter image description here

how to convert a single COCO JSON annotation file into a YOLO darknet format?? like below each individual image has separate filename.txt file enter image description here

Douzepers answered 15/7, 2021 at 18:18 Comment(0)
K
8

I built a tool https://github.com/tw-yshuang/coco2yolo

Download this repo and use the following command:

python3 coco2yolo.py [OPTIONS]

coc2yolo

Usage: coco2yolo.py [OPTIONS] [CAT_INFOS]...

Options:
  -ann-path, --annotations-path TEXT
                                  JSON file. Path for label.  [required]
  -img-dir, --image-download-dir TEXT
                                  The directory of the image data place.
  -task-dir, --task-categories-dir TEXT
                                  Build a directory that follows the task-required categories.
  -cat-t, --category-type TEXT    Category input type. (interactive | file)  [default: interactive]
  -set, --set-computing-type TEXT
                                  Set Computing for the data. (union | intersection)  [default: union]
  --help                          Show this message and exit.
Kelila answered 11/4, 2022 at 15:48 Comment(0)
S
7

My classmates and I have created a python package called PyLabel to help others with this task and other labelling tasks.

Our package does this conversion! You can see an example in this notebook https://github.com/pylabel-project/samples/blob/main/coco2yolov5.ipynb.

You're answer should be in there! But you should be able to do this conversion by doing something like:

!pip install pylabel
from pylabel import importer
dataset = importer.ImportCoco(path=path_to_annotations, path_to_images=path_to_images)
dataset.export.ExportToYoloV5(dataset)

You can find the source code that is used behind the scenes here https://github.com/pylabel-project/

Steading answered 20/11, 2021 at 7:7 Comment(2)
No it's not working, it converting it to YAML, not a txt file !Tacit
@Derek dataset.export.ExportToYoloV5(dataset): shouldn't the argument of ExportToYoloV5() method be something line ExportToYoloV5(output_path='./yolo') ?Gretchengrete
T
0

There is an open-source tool called makesense.ai for annotating your images. You can download YOLO txt format once you annotate your images. But you won't be able to download the annotated images.

Tauromachy answered 4/8, 2021 at 14:52 Comment(1)
This does not address the question. The question is how to convert an existing JSON formatted dataset to YAML format, not how to export a dataset into YAML format.Hyksos
C
0

This works for me

I have loaded all the images in images/all_images directory. I used coco .json annotations differently for train/test/val. You can change accordingly. Make sure to create directory accordingly.

import os
import json
import shutil

# load json and save directory for labels train/val/test
coco_file = 'labels/val.json'
save_folder = 'labels/val'



#source of all the images and destination folder for train/test/val
source_path = "images/all_images"
destination_path = "images/val"


# Use os.listdir() to get a list of filenames in the folder
file_names = os.listdir(source_path)

with open(coco_file) as f:
    coco = json.load(f)

images = coco['images']
annotations = coco['annotations'] 
categories = {cat['id']: cat['name'] for cat in coco['categories']}

#os.makedirs(save_folder, exist_ok=True)

for ann in annotations:
    image = next(img for img in images if (img['id'] == ann['image_id']))
    if (image["file_name"] not in file_names):
        continue
    #print(f"image in annotations =   {type(image['id'])}")
    width, height = image['width'], image['height']
    x_center = (ann['bbox'][0] + ann['bbox'][2] / 2) / width
    y_center = (ann['bbox'][1] + ann['bbox'][3] / 2) / height
    bbox_width = ann['bbox'][2] / width
    bbox_height = ann['bbox'][3] / height
    category_id = ann['category_id']
    image_id = ann['image_id']

    filename = image['file_name']
    label_filename = filename.split('.jpg')[0]
    label_path = os.path.join(save_folder, f'{label_filename}.txt')
    with open(label_path, 'a') as f:

        segmentation_points_list = []
        for segmentation in ann['segmentation']:
            # Check if any element in segmentation is a string
            if any(isinstance(point, str) for point in segmentation):
                continue  # Skip this segmentation if it contains strings

            segmentation_points = [str(float(point) / width) for point in segmentation]
            segmentation_points_list.append(' '.join(segmentation_points))
            segmentation_points_string = ' '.join(segmentation_points_list)
            line = '{} {}\n'.format(categories, segmentation_points_string)
            f.write(line)
            segmentation_points_list.clear()
    image_source = source_path + f'/{image["file_name"]}'
    shutil.copy(image_source, destination_path)
Corolla answered 1/10, 2023 at 17:32 Comment(0)
P
-7

There is three ways.

  1. use roboflow https://roboflow.com/formats (You can find another solution also) enter image description here

You can find some usage guide for roboflow. e.g. https://medium.com/red-buffer/roboflow-d4e8c4b52515

  1. search 'convert coco format to yolo format' -> you will find some open-source codes to convert annotations to yolo format.

  2. write your own code to convert coco format to yolo format

Polyhistor answered 13/11, 2022 at 23:10 Comment(1)
This is one of the methods to convert the file format but the data will be publicised.Sherrer

© 2022 - 2025 — McMap. All rights reserved.