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

时间:2021-05-22

代码使用说明

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

完整代码

from PIL import Imageimport osimport globimport numpy as npimport 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_numdef 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数据格式 (亲测有效)的文章就介绍到这了,更多相关json 转 mot17数据格式 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章