python生成lmdb格式的文件实例


Posted in Python onNovember 08, 2018

在crnn训练的时候需要用到lmdb格式的数据集,下面是python生成lmdb个是数据集的代码,注意一定要在linux系统下,否则会读入图像的时候出问题,可能遇到的问题都在代码里面注释了,看代码即可。

#-*- coding:utf-8 -*-
 
import os
import lmdb#先pip install这个模块哦
import cv2
import glob
import numpy as np
 
 
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 '...................'
 env = lmdb.open(outputPath, map_size=8589934592)#1099511627776)所需要的磁盘空间的最小值,之前是1T,我改成了8g,否则会报磁盘空间不足,这个数字是字节
 
 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)#注意一定要在linux下,否则f.read就不可用了,就会输出这个信息
    continue
 
  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
 
 
if __name__ == '__main__':
 # lmdb 输出目录
 outputPath = 'D:/ruanjianxiazai/tuxiangyangben/fengehou/train'#训练集和验证集要跑两遍这个程序,分两次生成
 
 path = "D:/ruanjianxiazai/tuxiangyangben/fengehou/chenguang/*.jpg"#将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 labelList
 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)

以上这篇python生成lmdb格式的文件实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
利用Python绘制数据的瀑布图的教程
Apr 07 Python
python通过自定义isnumber函数判断字符串是否为数字的方法
Apr 23 Python
深入浅析python继承问题
May 29 Python
Python有序字典简单实现方法示例
Sep 28 Python
PyCharm设置护眼背景色的方法
Oct 29 Python
python 处理数字,把大于上限的数字置零实现方法
Jan 28 Python
Python-接口开发入门解析
Aug 01 Python
python3 实现函数写文件路径的正确方法
Nov 27 Python
Python3.7+tkinter实现查询界面功能
Dec 24 Python
Python面向对象之多态原理与用法案例分析
Dec 30 Python
PIL.Image.open和cv2.imread的比较与相互转换的方法
Jun 03 Python
Python绘制K线图之可视化神器pyecharts的使用
Mar 02 Python
python实现嵌套列表平铺的两种方法
Nov 08 #Python
python用列表生成式写嵌套循环的方法
Nov 08 #Python
在Python中实现shuffle给列表洗牌
Nov 08 #Python
python实现RabbitMQ的消息队列的示例代码
Nov 08 #Python
对Python 3.5拼接列表的新语法详解
Nov 08 #Python
Python使用random.shuffle()打乱列表顺序的方法
Nov 08 #Python
python RabbitMQ 使用详细介绍(小结)
Nov 08 #Python
You might like
PHP学习笔记之字符串编码的转换和判断
2014/05/22 PHP
PHP文件锁函数flock()详细介绍
2014/11/18 PHP
PHP中header函数的用法及其注意事项详解
2016/06/13 PHP
PHP sdk文档处理常用代码示例解析
2020/12/09 PHP
jquery.AutoComplete.js中文修正版(支持firefox)
2010/04/09 Javascript
js数组转json并在后台对其解析具体实现
2013/11/20 Javascript
JQuery的$和其它JS发生冲突的快速解决方法
2014/01/24 Javascript
JavaScript合并两个数组并去除重复项的方法
2015/06/13 Javascript
JavaScript实现99乘法表及隔行变色实例代码
2016/02/24 Javascript
基于gulp合并压缩Seajs模块的方式说明
2016/06/14 Javascript
js removeChild 方法深入理解
2016/08/16 Javascript
node.js中http模块和url模块的简单介绍
2017/10/06 Javascript
jQuery+PHP实现上传裁剪图片
2020/06/29 jQuery
JS实现返回上一页并刷新页面的方法分析
2019/07/16 Javascript
微信小程序实现多选框功能的实例代码
2020/06/24 Javascript
详解React 条件渲染
2020/07/08 Javascript
python重试装饰器示例
2014/02/11 Python
高性能web服务器框架Tornado简单实现restful接口及开发实例
2014/07/16 Python
Python内置数据结构与操作符的练习题集锦
2016/07/01 Python
python爬虫入门教程--优雅的HTTP库requests(二)
2017/05/25 Python
利用pyinstaller将py文件打包为exe的方法
2018/05/14 Python
浅谈Python 列表字典赋值的陷阱
2019/01/20 Python
python多线程抽象编程模型详解
2019/03/20 Python
django 读取图片到页面实例
2020/03/27 Python
python构造IP报文实例
2020/05/05 Python
python对接ihuyi实现短信验证码发送
2020/05/10 Python
PyCharm设置注释字体颜色以及是否倾斜的操作
2020/09/16 Python
夏尔巴人登珠峰品牌:Sherpa Adventure Gear
2018/02/08 全球购物
奥兰多迪士尼门票折扣:Undercover Tourist
2018/07/09 全球购物
办公室文秘自我鉴定
2013/09/21 职场文书
《小松树和大松树》教学反思
2014/02/20 职场文书
理工学院学生自我鉴定
2014/02/23 职场文书
交通事故调解协议书
2014/04/16 职场文书
学期评语大全
2014/04/30 职场文书
推广普通话宣传标语口号
2015/12/26 职场文书
Redis 报错 error:NOAUTH Authentication required
2022/05/15 Redis