二、OCR训练时,将txt文件和图片数据转为lmdb文件格式
文章目录
- 前言
- 一、背景?
- 二、直接上内容
- 1.代码
- 2.文件说明
前言
随着人工智能的不断发展,机器学习这门技术也越来越重要,本文就介绍OCR训练前ldmb文件制作的基础内容。
提示:以下是本篇文章正文内容,下面案例可供参考
一、背景?
示例:是基于ocr训练而作。
二、直接上内容
1.代码
代码如下(示例):
# -*- coding:utf-8 -*-import os
import lmdb # ?pip install?????
import cv2
import glob #????????????
import numpy as npdef checkImageIsValid(imageBin):if imageBin is None:return FalseimageBuf = np.fromstring(imageBin, dtype=np.uint8)img = cv2.imdecode(imageBuf, cv2.IMREAD_GRAYSCALE)if img is None:return FalseimgH, imgW = img.shape[0], img.shape[1]if imgH * imgW == 0:return Falsereturn Truedef writeCache(env, cache):with env.begin(write=True) as txn:# for k, v in cache.iteritems(): #python2for k, v in cache.items(): #python3txn.put(k.encode(), str(v).encode())def createDataset(outputPath, imagePathList, labelList, lexiconList=None, checkValid=True):"""Create LMDB dataset for CRNN training.
# ARGS:outputPath : LMDB output pathimagePathList : list of image pathlabelList : list of corresponding groundtruth textslexiconList : (optional) list of lexicon listscheckValid : if true, check the validity of every image"""# print (len(imagePathList) , len(labelList))assert (len(imagePathList) == len(labelList))nSamples = len(imagePathList)print('...................')env = lmdb.open(outputPath, map_size=8589934592) # 1099511627776)????????????????1T?????8g???????????????????cache = {}cnt = 1for i in range(nSamples):imagePath = imagePathList[i]label = labelList[i]if not os.path.exists(imagePath):print('%s does not exist' % imagePath)continuewith open(imagePath, 'r') as f:imageBin = f.read()if checkValid:if not checkImageIsValid(imageBin):print('%s is not a valid image' % imagePath) # ??????linux????f.read??????????????continueimageKey = 'image-%09d' % cntlabelKey = 'label-%09d' % cntcache[imageKey] = imageBincache[labelKey] = labelif lexiconList:lexiconKey = 'lexicon-%09d' % cntcache[lexiconKey] = ' '.join(lexiconList[i])if cnt % 1000 == 0:writeCache(env, cache)cache = {}print('Written %d / %d' % (cnt, nSamples))cnt += 1nSamples = cnt - 1cache['num-samples'] = str(nSamples)writeCache(env, cache)print('Created dataset with %d samples' % nSamples)def read_text(path):with open(path) as f:text = f.read()text = text.strip()return textif __name__ == '__main__':# lmdb ????outputPath = r'E:\enducate\test_paper\Train_code\train' # ?????????????????????path = r"E:\enducate\test_paper\Train_code\data22222\*.png" # ?txt?jpg???????????imagePathList = glob.glob(path)print('------------', len(imagePathList), '------------')imgLabelLists = []for p in imagePathList:try:imgLabelLists.append((p, read_text(p.replace('.jpg', '.txt'))))except:continue# imgLabelList = [ (p, read_text(p.replace('.jpg', '.txt'))) for p in imagePathList]# sort by labelListimgLabelList = sorted(imgLabelLists, key=lambda x: len(x[1]))imgPaths = [p[0] for p in imgLabelList]txtLists = [p[1] for p in imgLabelList]createDataset(outputPath, imgPaths, txtLists, lexiconList=None, checkValid=True)
2.文件说明
第一种文件格式
图片路径和txt标签文件共存。(1张图片对应1个txt标签文件)
txt文件和图片是放在一个文件夹的。
第二种文件格式如下:
文件有多张图片和1个txt文件组成,其中txt文件是包括所有图片的标签。
格式为:图片路径名+\t+标签。
// A code block
var foo = 'bar';
// An highlighted block""" a modified version of CRNN torch repository https://github.com/bgshih/crnn/blob/master/tool/create_dataset.py """import fire
import os
import lmdb
import cv2import numpy as npdef checkImageIsValid(imageBin):if imageBin is None:return FalseimageBuf = np.frombuffer(imageBin, dtype=np.uint8)img = cv2.imdecode(imageBuf, cv2.IMREAD_GRAYSCALE)imgH, imgW = img.shape[0], img.shape[1]if imgH * imgW == 0:return Falsereturn Truedef writeCache(env, cache):with env.begin(write=True) as txn:for k, v in cache.items():txn.put(k, v)def createDataset(inputPath, gtFile, outputPath, checkValid=True):"""Create LMDB dataset for training and evaluation.ARGS:inputPath : input folder path where starts imagePathoutputPath : LMDB output pathgtFile : list of image path and labelcheckValid : if true, check the validity of every image"""os.makedirs(outputPath, exist_ok=True)env = lmdb.open(outputPath, map_size=1099511627776)cache = {}cnt = 1with open(gtFile, 'r', encoding='utf-8') as data:datalist = data.readlines()nSamples = len(datalist)for i in range(nSamples):imagePath, label = datalist[i].strip('\n').split('\t')# imagePath = os.path.join(inputPath, imagePath)# # only use alphanumeric data# if re.search('[^a-zA-Z0-9]', label):# continueif not os.path.exists(imagePath):print('%s does not exist' % imagePath)continuewith open(imagePath, 'rb') as f:imageBin = f.read()if checkValid:try:if not checkImageIsValid(imageBin):print('%s is not a valid image' % imagePath)continueexcept:print('error occured', i)with open(outputPath + '/error_image_log.txt', 'a') as log:log.write('%s-th image data occured error\n' % str(i))continueimageKey = 'image-%09d'.encode() % cntlabelKey = 'label-%09d'.encode() % cntcache[imageKey] = imageBincache[labelKey] = label.encode()if cnt % 1000 == 0:writeCache(env, cache)cache = {}print('Written %d / %d' % (cnt, nSamples))cnt += 1nSamples = cnt-1cache['num-samples'.encode()] = str(nSamples).encode()writeCache(env, cache)print('Created dataset with %d samples' % nSamples)if __name__ == '__main__':fire.Fire(createDataset)# python create_lmdb_dataset.py --inputPath /data2/ --gtFile /data2/meterdataset/digital_dataset/otherdataset/1030_data/collect_val.txt --outputPath /data2/meterdataset/digital_dataset/otherdataset/1030_data/2021-0507-result/val
第二个运行说明:
> 输入路径:inputPath 操作的文件夹
txt文件: gtFile
ldmb输出的文件路径: outputPath
// An highlighted block
python create_lmdb_dataset.py --inputPath /data2/ --gtFile /data2/enducation/paper_recog_total/train-paper-recog/Recognization/deep-text-recognition-SHENG/data/text_recog/txt4val/img_gt/gt.txt --outputPath /data2/enducation/paper_recog_total/train-paper-recog/Recognization/deep-text-recognition-SHENG/data/val
二、OCR训练时,将txt文件和图片数据转为lmdb文件格式相关推荐
- c++ 按行读取txt文件并赋值_python操作txt文件中数据教程[3]python读取文件夹中所有txt文件并将数据转为csv文件...
觉得有用的话,请点击右下角 推荐给更多小伙伴 neoken_xuAsurada2015Evacloud 参考文献 python 操作 txt 文件中数据教程[1]-使用 python 读写 txt 文 ...
- 用Python对我们自己标注的数据集转化为YOLO训练需要的txt文件
用Python对我们自己标注的数据集转化为YOLO训练需要的txt文件 一. 数据分类 在项目的根目录下新建一个maketxt.py文件. 该脚本会在straw/ImageSets文件夹下生成:tra ...
- c# cad二次开发 通过选择txt文件将自动转换成多段线
c# cad二次开发 通过选择txt文件将自动转换成多段线,txt样式如下 using System; using System.Collections.Generic; using System.T ...
- bulkwrite 批量插入_SQL SERVER 使用BULK Insert将txt文件中的数据批量插入表中(1)
1/首先建立数据表 CREATE TABLE BasicMsg ( RecvTime FLOAT NOT NULL , --接收时间,不存在时间相同的数据 AA INT NOT NULL, --24位 ...
- 如何用c语言从txt文件中读取数据
用C语言从txt文件中读取数据,可以使用C标准库文件自带的文件接口函数进行操作. 一.打开文件: FILE *fopen(const char *filename, const char *mode) ...
- python文本筛选_使用python对多个txt文件中的数据进行筛选的方法
使用python对多个txt文件中的数据进行筛选的方法 一.问题描述 筛选出多个txt文件中需要的数据 二.数据准备 这是我自己建立的要处理的文件,里面是随意写的一些数字和字母 三.程序编写 impo ...
- C++实现从.txt文件中读取数据存入数组,将数组数据写入.txt文件
声明: 编译器:vs2017 所有用到的.txt文件都是提前放在当前工程目录下的. 完整测试代码:github–Zhaotiedan 方法一:针对可以提前知道存入数组的大小 1.从.txt文件中读取数 ...
- Python——读取txt文件每一行数据
Python--读取txt文件每一行数据生成列表 一.例子1 (间隔符:逗号) 1.1 文件 1.2 代码 1.3 结果 二.例子2 (间隔符:空格) 2.1 文件 2.2 代码 2.3 结果 参考文 ...
- vc++向txt文件中写入数据,追加数据
例子: #include<iostream> #include<stdio.h> using namespace std; int main() { //将矩阵写在文件上 fl ...
最新文章
- leetcode63. Unique Paths II
- 记录Pandas处理数据的两个小技巧
- asp.net页面出错时的处理方法
- 面试题57 - II. 和为s的连续正数序列 golang
- 一枚戒指,一场仪式,这件事阿里巴巴坚持了15年
- php 链接远程oracle,PHP连接远程oracle输出数据
- matlab曲线拟合 新浪,Matlab曲线拟合
- js获取对象数组中指定属性值对象_3分钟学会操作JavaScript内置对象,快来试试吧...
- 动力环境监控系统论文_浅析建设智能化动力环境监控系统维护水平论文
- GRE阅读高频机经原文及答案之鸟叫研究
- 操作系统课程设计之页面置换算法(流程模拟)
- Java 转换成ObjectC代码
- 隐马尔可夫模型python_隐马尔可夫模型HMM及Python实现
- 监控摄像头镜头大小的区别
- 易中天品汉代风云人物02: 冤死的晁错(下)
- Android 检索相册视频文件
- hacker与cracker区别
- 自动驾驶中的SLAM
- 背着房贷被裁员是一种什么样的体验?
- python中char是什么意思_MySQL中char和varchar的区别是什么