I want to convert json format data to txt format data to use yolo.
The code to convert json to txt was on the net, but I didn't know how to use it, so I decided to create it myself. (I may have seen it because I cut and pasted a part of various codes)
import json
import glob
data_path = glob.glob("train_json/*.json")
img_data_path = glob.glob("train_img/*.jpg ")
cate_list = ["Car","Pedestrian","Truck","Signal","Signs","Bicycle","Motorbike","Bus","Svehicle","Train"]
box_list = ["x1","x2","y1","y2"]
input_shape = [640,640]
img_output = "train_img_data"
with open("voc_classes.txt","w") as f:
f.write('\n'.join(cate_list))
list_file = open("2007_train.txt","w")
def class_encord(class_name):
cate_id = {"Car":0,"Pedestrian":1,"Truck":2,"Signal":3,"Signs":4,"Bicycle":5,"Motorbike":6,"Bus":7,"SVehicle":8,"Train":9}
return cate_id[class_name]
def img_box_resize(img_path,input_shape,label_box):
img = Image.open(img_path)
iw , ih = img.size
w, h = input_shape
scale = min(w/iw,h/ih)
nw = int(scale*iw)
nh = int(scale*ih)
dx = (w-nw)//2
dy = (h-nh)//2
img_data = 0
image = img.resize((nw,nh),Image.BICUBIC)
new_image = Image.new("RGB", (w,h), (128,128,128))
new_image.paste(image, (dx, dy))
bax_lx = label_box[0]
box_ly = label_box[1]
box_rx = label_box[2]
box_ry = label_box[3]
new_box_lx = int(box_lx*scale) + int(dx)
new_box_ly = int(box_ly*scale) + int(dy)
new_box_rx = int(box_rx*scale) - int(dx)
new_box_ry = int(box_ry*scale) - int(dy)
box_list = []
box_list.append(new_box_lx)
box_list.append(new_box_ly)
box_list.append(new_box_rx)
box_list.append(new_box_ry)
return new_image , box_list
def convert(data_file,list_file,input_img_path,output_img_path):
with open(data_file) as j_f:
load_json = json.load(j_f)
datas = load_json["labels"]
for data in datas:
box = data["box2d"]
json_box = []
new_img , box_list = img_box_resize(img_path,input_shape,box)
for i in range(4):
json_box.append(box_list[i])
category = data["category"]
category_num = class_encord(category)
list_file.write(" "+",".join([str(a) for a in json_box])+","+str(category_num))
new_img.save(output_img_path+"/"+input_img_path)
for data_file in data_path:
for img_path in img_data_path:
data = data_file
list_file.write(output_img_path+"/"+input_img_path)
convert(data_file,list_file,img_path,img_output)
list_file.write("\n")
list_file.close()
Please change according to the environment where the above variables are used. It will be converted according to the size of input_shape.
Should work: sweat_smile: (I worked with this)
Recommended Posts