how to convert a single COCO JSON annotation file into a YOLO darknet format?? like below each individual image has separate filename.txt file
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.
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/
dataset.export.ExportToYoloV5(dataset)
: shouldn't the argument of ExportToYoloV5()
method be something line ExportToYoloV5(output_path='./yolo')
? –
Gretchengrete 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.
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)
There is three ways.
- use roboflow https://roboflow.com/formats (You can find another solution also)
You can find some usage guide for roboflow. e.g. https://medium.com/red-buffer/roboflow-d4e8c4b52515
search 'convert coco format to yolo format' -> you will find some open-source codes to convert annotations to yolo format.
write your own code to convert coco format to yolo format
© 2022 - 2025 — McMap. All rights reserved.