import json
import os
from os import listdir, getcwd
from os. path import join
import os. pathrootdir = 'F:/dataset/'
input_dir = 'F:/dataset/labels_json /'
output_dir = 'F:/dataset/labels_box/'
def position ( pos) : x = [ ] y = [ ] nums = len ( pos) for i in range ( nums) : x. append( pos[ i] [ 0 ] ) y. append( pos[ i] [ 1 ] ) x_max = max ( x) x_min = min ( x) y_max = max ( y) y_min = min ( y) b = ( float ( x_min) , float ( x_max) , float ( y_min) , float ( y_max) ) return bdef convert_annotation ( image_ids, input_dir, output_dir) : for image_id in image_ids: print ( image_id) input_file_path = os. path. join( input_dir, f" { image_id} .json " ) output_file_path = os. path. join( output_dir, f" { image_id} .json " ) try : with open ( input_file_path, 'r' ) as load_f: load_dict = json . load( load_f) w = load_dict[ 'imageWidth' ] h = load_dict[ 'imageHeight' ] objects = load_dict[ 'shapes' ] annotations = [ ] for obj in objects: labels = obj[ 'label' ] . strip( ) if labels in [ "class1" , "class2" , "class3" , "class4" ] : pos = obj[ 'points' ] b = position( pos) cls_id_mapping = { "class1" : 1 , "class2" : 2 , "class3" : 3 , "class4" : 4 , } cls_id = cls_id_mapping[ labels] annotation = { 'label' : labels, 'class_id' : cls_id, 'bbox' : b} annotations. append( annotation) output_dict = { "version" : "5.0.2" , "flags" : { } , "shapes" : [ ] , "imagePath" : load_dict[ 'imagePath' ] , "imageData" : None , "imageHeight" : h, "imageWidth" : w, "annotations" : annotations } for shape in load_dict[ 'shapes' ] : objects = load_dict[ 'shapes' ] for obj in objects: labels = obj[ 'label' ] . strip( ) if labels in [ "class1" , "class2" , "class3" , "class4" ] : pos = obj[ 'points' ] b = position( pos) rect_points = [ [ b[ 0 ] , b[ 3 ] ] , [ b[ 1 ] , b[ 2 ] ] ] new_shape = { "label" : labels, "points" : rect_points, "group_id" : None , "shape_type" : "rectangle" , "flags" : { } } output_dict[ 'shapes' ] . append( new_shape) with open ( output_file_path, 'w' ) as output_f: json . dump( output_dict, output_f, indent= 4 ) except Exception as e: print ( f"Error processing { input_file_path} : { e} " ) def image_id ( rootdir) : a = [ ] for parent, dirnames, filenames in os. walk( rootdir) : for filename in filenames: if filename. endswith( '.jpg' ) : filename = os. path. splitext( filename) [ 0 ] if filename. endswith( '.jpeg' ) : filename = os. path. splitext( filename) [ 0 ] if filename. endswith( '.JPG' ) : filename = os. path. splitext( filename) [ 0 ] if filename. endswith( '.JPEG' ) : filename = os. path. splitext( filename) [ 0 ] a. append( filename) return anames = image_id( "F:/dataset/images/" ) , for image_id in names: convert_annotation( image_id, input_dir, output_dir)