我的做法是自制一个labelme标注的json模板,基于这个模板来进行转换
#coding:utf-8
import json
import cv2
import base64
def writeToJson(filePath,data):
fb = open(filePath,'w')
# json.dumps(data).decode('unicode-escape')
fb.write(json.dumps(data,indent=2,ensure_ascii=False)) # ,encoding='utf-8'
fb.close()
#转base64
def image_to_base64(image_np):
image = cv2.imencode('.jpg', image_np)[1]
image_code = str(base64.b64encode(image))[2:-1]
return image_code
def readJson(jsonfile):
with open(jsonfile,'r') as f:
jsonData = json.load(f)
return jsonData
def txt2json(imagePath,txtPath,savePath,contentJson):
TempList = []
PointSet = []
jsonDic = {}
image = cv2.imread(imagePath)
h, w, c = image.shape
labelText = "招牌***"
with open(txtPath) as f:
line = f.readlines()
for item in line:
PointList = item.rstrip().split(",")
TempList.append(PointList)
# print(PointList)
for item in TempList:
PointTemp = []
for j in range(len(item)):
temp = []
if (j + 1) % 2 == 0:
# print((j+1)%2)
temp.append(float(item[j - 1]))
temp.append(float(item[j]))
# print(temp)
PointTemp.append(temp)
temp = []
PointSet.append(PointTemp)
for key, value in contentJson.items():
if key == 'shapes':
temp = []
for item2 in PointSet:
jsonList = {}
for item in contentJson[key]:
for key2, value2 in item.items():
if key2 == "label":
jsonList[key2] = labelText
elif key2 == "points":
jsonList[key2] = item2
print(item2)
else:
jsonList[key2] = value2
temp.append(jsonList)
jsonDic[key] = temp
elif key == "imagePath":
jsonDic[key] = value
elif key == "imageData":
jsonDic[key] = image_to_base64(image)
elif key == "imageHeight":
jsonDic[key] = h
elif key == "imageWidth":
jsonDic[key] = w
else:
jsonDic[key] = value
writeToJson(savePath, jsonDic)
if __name__=='__main__':
contentJson=readJson('E:/icdar2013/test/demo.json')
imagePath="E:/icdar2013/test/666bd8a0e486ff0386d51c807019cff9913532.jpg"
txtPath="E:/icdar2013/test/666bd8a0e486ff0386d51c807019cff9913532.txt"
savePath="E:/icdar2013/test/hh.json"
txt2json(imagePath,txtPath,savePath,contentJson)