Icdar2015的txt转json(labelme可查看)

我的做法是自制一个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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值