PPOCR是个好东西,默认的训练文件是用自带的PPOCRLabel标注的,有时候需要用labelme来修改一些东西,比如后期用到的字段提取,就需要加一个参数,PPOCRLabel就没法做了,只能转成labelme,并利用group_id这个参数来赋值。所以,写了下面这个脚本,Label.txt每一行对应一个图片标注,该脚本作用是将PPOCRLabel的标注文件Label.txt转换为一个一个的json文件,并存储至json1目录下:
# -*- coding:utf-8 -*-
# 开发人员 : csu·攀-_-||
# 开发时间 : 2021/9/7 0007 10:30
# 文件名称 : pplable2json.py
# 开发工具 : PyCharm
# 功能描述 : PPOCRLabel标注的txt格式转换成labelme能修改的json格式
import os
import cv2
import json
import base64
#转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 pp2json(path,savepath):
with open(os.path.join(path,'Label.txt'),'r',encoding='utf-8') as f:
for line in f.readlines():
line = line.strip('\n') # 去掉列表中每一个元素的换行符
imgname = line.split('\t')[0].split('/')[1]
img = cv2.imread(os.path.join(path,imgname))
H,W,C = img.shape
items = json.loads(line.split('\t')[1])
item_shapes = []
for item in items:
item_shapes.append({
"label":item['transcription'],
"points":item['points'],
"group_id": 0,
"shape_type": "polygon",
"flags": {}
})
new_dict = {
"version": "4.5.9",
"flags": {},
"shapes": item_shapes,
"imagePath": imgname,
"imageData": image_to_base64(img),
"imageHeight": H,
"imageWidth": W
}
with open(os.path.join(savepath,imgname.split('.')[0] + '.json'), "w",encoding='utf-8') as fw:
print(imgname,' succeed!')
json.dump(new_dict, fw)
if __name__ == '__main__':
path = r'E:\Projects\OCR-release-2.1\tools\infer\imgs\train_data'
savepath = r'json1'
pp2json(path,savepath)
PPOCRLabel标注的Label.txt文件,所有的图片标注都在一个txt里头,一个图片一行,文件名和标注内容之间用制表符’\t’隔开。
labelme标注的json文件格式