import os
import json
LABEL_DIR = "D:\ChromeDownload\***"
OUTPUT_DIR = "D:\ChromeDownload\labels"
IMAGE_WIDTH = 1920
IMAGE_HEIGHT = 1080
CLASS_MAP = { "Car" : 0 , "Truck" : 1 , "Van" : 2 , "Bus" : 3 , "Pedestrian" : 4 , "Cyclist" : 5 , "Tricyclist" : 6 , "Motorcyclist" : 7 , "Barrowlist" : 8
} def convert_bbox_to_yolo ( xmin, ymin, xmax, ymax, img_w, img_h) : x_center = ( xmin + xmax) / 2.0 / img_wy_center = ( ymin + ymax) / 2.0 / img_hwidth = ( xmax - xmin) / img_wheight = ( ymax - ymin) / img_hreturn x_center, y_center, width, height
def convert_json_to_txt ( json_path, txt_path) : with open ( json_path, 'r' ) as f: data = json. load( f) lines = [ ] for obj in data: cls = obj. get( "type" ) if cls not in CLASS_MAP: continue bbox = obj. get( "2d_box" ) xmin = bbox[ "xmin" ] ymin = bbox[ "ymin" ] xmax = bbox[ "xmax" ] ymax = bbox[ "ymax" ] x_c, y_c, w, h = convert_bbox_to_yolo( xmin, ymin, xmax, ymax, IMAGE_WIDTH, IMAGE_HEIGHT) x_c = max ( min ( x_c, 1 ) , 0 ) y_c = max ( min ( y_c, 1 ) , 0 ) w = max ( min ( w, 1 ) , 0 ) h = max ( min ( h, 1 ) , 0 ) cls_id = CLASS_MAP[ cls] lines. append( f" { cls_id} { x_c: .6f } { y_c: .6f } { w: .6f } { h: .6f } " ) if lines: with open ( txt_path, "w" ) as f: f. write( "\n" . join( lines) ) else : with open ( txt_path, "w" ) as f: pass def main ( ) : os. makedirs( OUTPUT_DIR, exist_ok= True ) for filename in os. listdir( LABEL_DIR) : if not filename. endswith( ".json" ) : continue json_path = os. path. join( LABEL_DIR, filename) txt_filename = os. path. splitext( filename) [ 0 ] + ".txt" txt_path = os. path. join( OUTPUT_DIR, txt_filename) convert_json_to_txt( json_path, txt_path) print ( f"Converted { filename} -> { txt_filename} " ) if __name__ == "__main__" : main( )