CRNN简介

CRNN由 Baoguang Shi, Xiang Bai, Cong Yao提出,2015年7月发表论文:“An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition”,链接地址:https://arxiv.org/abs/1507.05717v1

CRNN(卷积循环神经网络)集成了卷积神经网络(CNN)和循环神经网络(RNN)的优点。CRNN可以直接从序列标签(例如单词,句子)中学习,不需要详细的单个分别标注,并且对图像序列对象的长度无限定,只需要在训练和测试阶段对图像高度做一下归一化。于现有技术相比,CRNN在场景文本识别上表现良好。

CRNN中训练数据的格式是LMDB,保存了两种数据,一种是图片数据,一种是标签数据,它们各有其key,如下所示:



准备CRNN训练数据集

数据集图片是若干带有文字的图片,文字的高度约占图片高度的80%~90%,数据集标签是txt文本格式,文本内容是图片上的文字,文本名字要跟图片名字一致,如123.jpg对应标签需要是123.txt。

例如有 01.jpg 和 02.jpg 两个样本,标签文件是 01.txt 和 02.txt :

创建用于CRNN训练的LMDB数据

# -*- coding: utf-8 -*-
import os
import lmdb # install lmdb by "pip install lmdb"
import cv2
import numpy as np
#from genLineText import GenTextImage def checkImageIsValid(imageBin):
if imageBin is None:
return False
imageBuf = np.fromstring(imageBin, dtype=np.uint8)
img = cv2.imdecode(imageBuf, cv2.IMREAD_GRAYSCALE)
if img is None:
return False
imgH, imgW = img.shape[0], img.shape[1]
if imgH * imgW == 0:
return False
return True def writeCache(env, cache):
with env.begin(write=True) as txn:
for k, v in cache.iteritems():
txn.put(k, v) def createDataset(outputPath, imagePathList, labelList, lexiconList=None, checkValid=True):
"""
Create LMDB dataset for CRNN training. ARGS:
outputPath : LMDB output path
imagePathList : list of image path
labelList : list of corresponding groundtruth texts
lexiconList : (optional) list of lexicon lists
checkValid : if true, check the validity of every image
"""
#print (len(imagePathList) , len(labelList))
assert(len(imagePathList) == len(labelList))
nSamples = len(imagePathList)
print '...................'
# map_size=1099511627776 定义最大空间是1TB
env = lmdb.open(outputPath, map_size=1099511627776) cache = {}
cnt = 1
for i in xrange(nSamples):
imagePath = imagePathList[i]
label = labelList[i]
if not os.path.exists(imagePath):
print('%s does not exist' % imagePath)
continue
with open(imagePath, 'r') as f:
imageBin = f.read()
if checkValid:
if not checkImageIsValid(imageBin):
print('%s is not a valid image' % imagePath)
continue ########## .mdb数据库文件保存了两种数据,一种是图片数据,一种是标签数据,它们各有其key
imageKey = 'image-%09d' % cnt
labelKey = 'label-%09d' % cnt
cache[imageKey] = imageBin
cache[labelKey] = label
##########
if lexiconList:
lexiconKey = 'lexicon-%09d' % cnt
cache[lexiconKey] = ' '.join(lexiconList[i])
if cnt % 1000 == 0:
writeCache(env, cache)
cache = {}
print('Written %d / %d' % (cnt, nSamples))
cnt += 1
nSamples = cnt-1
cache['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 text import glob
if __name__ == '__main__': #lmdb 输出目录
outputPath = '../data/lmdb/trainMy' # 训练图片路径,标签是txt格式,名字跟图片名字要一致,如123.jpg对应标签需要是123.txt
path = '../data/dataline/*.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 lebelList
imgLabelList = 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)

读取LMDB数据集中图片

# -*- coding: utf-8 -*-
import numpy as np
import lmdb
import cv2 with lmdb.open("../data/lmdb/train") as env:
txn = env.begin()
for key, value in txn.cursor():
print (key,value)
imageBuf = np.fromstring(value, dtype=np.uint8)
img = cv2.imdecode(imageBuf, cv2.IMREAD_GRAYSCALE)
if img is not None:
cv2.imshow('image', img)
cv2.waitKey()
else:
print 'This is a label: {}'.format(value)

Python创建CRNN训练用的LMDB数据库文件的更多相关文章

  1. python中读写LMDB数据库

    LMDB的全称是Lightning Memory-Mapped Database(快如闪电的内存映射数据库),它的文件结构简单,包含一个数据文件和一个锁文件: LMDB文件可以同时由多个进程打开,具有 ...

  2. 【PyTorch】PyTorch使用LMDB数据库加速文件读取

    PyTorch使用LMDB数据库加速文件读取 原始文档:https://www.yuque.com/lart/ugkv9f/hbnym1 对于数据库的了解较少,文章中大部分的介绍主要来自于各种博客和L ...

  3. python模块之bsddb: bdb高性能嵌入式数据库 1.基础知识

    转自:http://blog.csdn.net/zhaoweikid/article/details/1665741 bsddb模块是用来操作bdb的模块,bdb是著名的Berkeley DB,它的性 ...

  4. python生成数据后,快速导入数据库

    1.使用python生成数据库文件内容 # coding=utf-8import randomimport time def create_user():    start = time.time() ...

  5. python创建MySQL多实例-1

    python创建MySQL多实例-1 前言 什么是多实例 多实例就是允许在同一台机器上创建另外一套不同配置文件的数据库,他们之间是相互独立的,主要有以下特点, 1> 不能同时使用一个端口 2&g ...

  6. 使用python创建mxnet操作符(网络层)

    对cuda了解不多,所以使用python创建新的操作层是个不错的选择,当然这个性能不如cuda编写的代码. 在MXNET源码的example/numpy-ops/下有官方提供的使用python编写新操 ...

  7. 【python】用 sqlacodegen 将存在的数据库表 转化成model.py

    Flask的sqlalchemy对数据库表的模型提供了很多易用的方法.为了使用这些内容,需要将数据库表按照Flask识别的格式创建成Model,但是一般我们都是在已经创建好的数据库环境中开发Pytho ...

  8. python创建项目

    一.准备下载 python3.6.6 https://www.python.org/downloads/windows/(需要注意你的电脑是32位还是64位) mysql 5.1.72 https:/ ...

  9. Python学习笔记:sqlite3(sqlite数据库操作)

    对于数据库的操作,Python中可以通过下载一些对应的三方插件和对应的数据库来实现数据库的操作,但是这样不免使得Python程序变得更加复杂了.如果只是想要使用数据库,又不想下载一些不必要的插件和辅助 ...

随机推荐

  1. 常用的Issue解决方案(EF框架)

    1.提交出错:ObjectStateManager 中已存在具有同一键的对象.    ObjectStateManager 无法跟踪具有相同键的多个对象. 遇到此问题,首先要确定的是主键是否赋值,以及 ...

  2. webservice -- cxf客户端调用axis2服务端

    背景: 有个项目, 需要由第三方提供用户信息, 实现用户同步操作, 对方给提供webservice接口(axis2实现)并也使用axis2作主客户端调用我方提供的webservice接口 起初, 由于 ...

  3. UVALive 6906 A - Cluster Analysis

    思路:排个序,依次选就好了. #include <bits/stdc++.h> #define PB push_back #define MP make_pair using namesp ...

  4. 使用阿里的maven库

    快使用阿里云的maven仓库 自从开源中国的maven仓库挂了之后就一直在用国外的仓库,慢得想要砸电脑的心都有了.如果你和我一样受够了国外maven仓库的龟速下载?快试试阿里云提供的maven仓库,从 ...

  5. 织梦DedeCMS实现 三级栏目_二级栏目_一级栏目_网站名称 的效果代码

    1.将官方原来的排列方式反过来,找到include/typelink.class.php第164行 $this->valuePositionName = $tinfos['typename']. ...

  6. struts2——多文件上传

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  7. 如何在MyEclipse中更改servlet模板 Jsp模板

    http://blog.csdn.net/sjw890821sjw/article/details/6995190 刚换上Myeclipse9.0,结果要修改servlet模板的时候不像Myeclps ...

  8. Python连接MongoDB操作

    1.安装PyMongo 注意:请勿安装“bson”软件包. PyMongo配有自己的bson包; 执行“pip install bson”或“easy_install bson”则会安装与PyMong ...

  9. LeetCode第[4]题(Java):Median of Two Sorted Arrays (俩已排序数组求中位数)——HARD

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

  10. SSL和SSH的区别

    SSL是一种国际标准的加密及身份认证通信协议,您用的浏览器就支持此协议.SSL(Secure Sockets Layer)最初是由美国Netscape公司研究出来的,后来成为了Internet网上安全 ...