vietanhdev / anylabeling

Effortless AI-assisted data labeling with AI support from YOLO, Segment Anything, MobileSAM!!
https://anylabeling.nrl.ai
GNU General Public License v3.0
2k stars 218 forks source link

How to save labels in yolo fomat #156

Open jugal-sheth opened 7 months ago

jugal-sheth commented 7 months ago

instead of saving labels as json file i need to save it in YOLO format

marcocaggioni commented 2 months ago

to convert the json label to the yolo txt labels I use:

import json
from pathlib import Path

def create_yolo_label(file, class_dict):

    with open(file, "r") as json_file:
        data = json.load(json_file)

    height=data['imageHeight']
    width=data['imageWidth']

    with open(f"{file.stem}.txt", "a") as yolo_label_file:
        for segment in data['shapes']:
            label_index=class_dict[segment['label']]
            label_line = f'{label_index} ' + ' '.join(f'{x/width} {y/height} ' for x,y in segment['points'])
            yolo_label_file.write(f'{label_line}\n')

filelist=list(Path('./').glob('*.json'))
class_dict={'dog':0} #example sigle class

for file in filelist:
    create_yolo_label(file, class_dict=class_dict)

this script will look for all the json files in the folder and save for each a .txt file in the yolov8 format