假如json文件如下
{
"tep": {},
"shapes": [
{
"label": "pen",
"points": [
[
1,
2
],
[
3,
4
]
]
}
],
"imageHeight": 1536,
"imageWidth": 2048
}
一个文件夹下都是json文件,**
不废话,看代码
# coding=utf-8
import sys
import time
import os
import numpy as np
import time
import gzip
import datetime
import cv2
import json
class data:
def __init__(self):
self.filelist=[]
self.imglist=[]
self.dstdir = "D:\\src\\"
self.srcdir = "D:\\dst\\"
self.dstfile=""
self.content=""
def getfilelist(self , file):
for root, dirs, files in os.walk(file):
for f in files:
m = os.path.join(root, f)
ss=os.path.splitext(m)
print("ss = ",ss)
dirname = ss[0]#文件夹
filetype = ss[1]
print("dirname = ",dirname)
print("filetype = ",filetype)
if(filetype == '.json'):
self.filelist.append(m)
if(filetype == '.jpg'):
self.imglist.append(m)
# 修改json文件坐标
def changefilejson(self):
for f in self.filelist:
srcfilename = os.path.basename(f)#文件名,带后缀
self.dstfile = self.dstdir+srcfilename
with open(f,"r") as fhandler:
self.content = json.loads(fhandler.read())
# print(self.content)
t1 = self.content["shapes"][0]["points"][0][0]
t2 = self.content["shapes"][0]["points"][0][1]
self.content["shapes"][0]["points"][0][0] = self.content["imageWidth"]-t1
self.content["shapes"][0]["points"][0][1] = self.content["imageHeight"]-t2
t1 = self.content["shapes"][0]["points"][1][0]
t2 = self.content["shapes"][0]["points"][1][1]
self.content["shapes"][0]["points"][1][0] = self.content["imageWidth"]-t1
self.content["shapes"][0]["points"][1][1] = self.content["imageHeight"]-t2
self.content["imageData"]=None
with open(self.dstfile,"w") as whandler:
json.dump(self.content, whandler, indent = 4, ensure_ascii=False)
def func():
# //1、获取所有文件
# //2、修改文件内容
# //3、写入新文件
ls = data()
ls.getfilelist(ls.srcdir)
ls.changefilejson()
if __name__ == '__main__':
func()