How can I convert a JSON file to TXT format locally for YOLO object detection training?

I have a dataset in .json format that I need to use for training an object detection model using the YOLO algorithm. To do that, I need to convert the JSON annotations to .txt format, specifically into the format YOLO expects.

I’d prefer not to use any online tools or converters. I want to handle the conversion entirely on my local machine. What’s the best way to convert JSON to TXT for YOLO training? Any script examples or guidance would be super helpful.

I’ve had some hands-on experience working with COCO-style datasets, and yeah—it’s pretty straightforward to convert a JSON file to TXT format locally for YOLO object detection training. Just extract the bounding boxes and normalize like this:

import json

with open('annotations.json') as f:
    data = json.load(f)

for ann in data['annotations']:
    image_id = ann['image_id']
    category_id = ann['category_id']
    x, y, w, h = ann['bbox']
    
    # Normalize
    x_center = (x + w / 2) / 1280
    y_center = (y + h / 2) / 720
    w /= 1280
    h /= 720

    with open(f'labels/{image_id}.txt', 'a') as out_file:
        out_file.write(f"{category_id} {x_center} {y_center} {w} {h}\n")

Just tweak the image size as per your dataset. A decent starting point for when you need to convert a JSON file to TXT format locally for YOLO object detection training.

Yup, and if you’re using something like LabelMe, it’s a bit trickier. Been there too. Every tool structures JSON differently, so you’ll likely parse shapes instead of bounding boxes. When I had to convert a JSON file to TXT format locally for YOLO object detection training, I first created a label-to-ID dictionary, it made mapping class names to YOLO indices way easier.

Also, remember: LabelMe uses polygon points, so you’ll need to compute bounding boxes from those. A few extra steps, but once it’s automated, you’re good to go for bulk conversion.

Been deep in this space too, and sometimes I skip reinventing the wheel. There are GitHub converters that’ll help you convert a JSON file to TXT format locally for YOLO object detection training, especially for COCO or LabelMe. But building your own script gives better control, especially when debugging weird labeling issues.

One important reminder: always verify whether your coordinates are in absolute or relative values. And don’t forget, some annotation tools invert the Y-axis. It’s a small thing that can make a big mess during training if overlooked.