网络编程
位置:首页>> 网络编程>> Python编程>> json 转 mot17数据格式的实现代码 (亲测有效)

json 转 mot17数据格式的实现代码 (亲测有效)

作者:G果  发布时间:2022-03-06 09:23:53 

标签:json,mot17,格式

代码使用说明

1970-2270文件夹是保存图像和json文件(也就是需要进行转换的文件)
det文件夹是保存单个json对应的txt(因为np.savetxt函数只能进行单个数组的保存)
det.txt文件是整合det文件夹所有txt文件(mot17数据集格式)

json 转 mot17数据格式的实现代码 (亲测有效)

完整代码


from PIL import Image
import os
import glob
import numpy as np
import json

#读取图片,修改图片,另存图片
def convertjpg(jpgfile,outdir,img_sum=0):
 img=Image.open(jpgfile)#提取目录下所有图片
 try:
   img_sum=str('%08d'%img_sum)#图片保存成00000001格式
   img.save(os.path.join(outdir)+img_sum+'.jpg')#保存到另一目录
 except Exception as e:
   print(e)

#读取文件名
def file_name(file_dir):  
 L=[]#保存文件名
 img_num=0#计算图片总数
 for root, dirs, files in os.walk(file_dir):
   img_num=img_num+len(files)
   one=os.path.basename(str(root))#获取路径最后的/或者\后的文件名
   L.append(one)
 num=len(L)-1 #获取路径下文件个数
 print('%s路径下有%d个文件'%(L[0],num))
 return L ,num ,img_num

def json2det(json_dir,out_dir,json_num):
 with open(json_dir,'r') as f:
   data_dict = json.load(f)
 '''5行5个目标,6列(类别索引、框左上角x坐标、框左上角y坐标、框的宽、框的高、目标置信度100)'''
 data=np.zeros([5,6])
 for i in range(len(data_dict["shapes"])):#遍历一个json中的所有目标
   points = np.array(data_dict["shapes"][i]["points"])
   xmin=min(points[:,0])
   ymin=min(points[:,1])
   xmax=max(points[:,0])
   ymax=max(points[:,1])

data[i,0]=json_num
   data[i,1]=xmin
   data[i,2]=ymin
   data[i,3]=xmax-xmin
   data[i,4]=ymax-ymin
   data[i,5]=100
 print(data)

a=np.linspace(-1,-1,len(data))
 data=np.insert(data,1,a,axis=1)#行矩阵插入
 a=a.reshape((len(a),1))
 data=np.concatenate((data,a,a,a),axis = 1)#补充-1
 print(data,'\n')    
 np.savetxt(out_dir,data,fmt="%d,%d,%.3f,%.3f,%.3f,%.3f,%.3f,%d,%d,%d",delimiter="\n")

def main():  
 i=0
 data_dir='E:/DL/CSDN-blog/json2mot17'
 for jsonfile in glob.glob(data_dir+'/1970-2270/'+'*.json'):
   i=i+1
   json2det(jsonfile,data_dir+'/det/'+str(i)+'.txt',i)
 print('det.txt生成完成')

det=open(data_dir+'/det.txt','w')
 for txts in range(300):
   print(txts)
   one_det=open(data_dir+'/det/'+str(txts+1)+'.txt').read()
   det.write(one_det)

det.close()

if __name__ == '__main__':
 main()

代码执行结果

json 转 mot17数据格式的实现代码 (亲测有效)

来源:https://blog.csdn.net/weixin_42899627/article/details/114851196

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com