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制作简易注册登录系统
Dec 15 Python
Python实现去除列表中重复元素的方法小结【4种方法】
Apr 27 Python
使用python判断你是青少年还是老年人
Nov 29 Python
在Pycharm中执行scrapy命令的方法
Jan 16 Python
Python创建或生成列表的操作方法
Jun 19 Python
python里运用私有属性和方法总结
Jul 08 Python
python基础 range的用法解析
Aug 23 Python
Python3加密解密库Crypto的RSA加解密和签名/验签实现方法实例
Feb 11 Python
解决python运行效率不高的问题
Jul 20 Python
10个顶级Python实用库推荐
Mar 04 Python
AI:如何训练机器学习的模型
Apr 16 Python
pandas中对文本类型数据的处理小结
Nov 01 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
Mysql中limit的用法方法详解与注意事项
2008/04/19 PHP
深入php var_dump()函数的详解
2013/06/05 PHP
PHP从二维数组得到N层分类树的实现代码
2016/10/11 PHP
thinkphp框架表单数组实现图片批量上传功能示例
2020/04/04 PHP
js改变文章字体大小的实例代码
2013/11/27 Javascript
使用AOP改善javascript代码
2015/05/01 Javascript
基于Echarts 3.19 制作常用的图形(非静态)
2016/05/19 Javascript
浅谈Sublime Text 3运行JavaScript控制台
2016/06/06 Javascript
JS图片定时翻滚效果实现方法
2016/06/21 Javascript
JS+HTML5实现的前端购物车功能插件实例【附demo源码下载】
2016/10/17 Javascript
修改ligerui 默认确认按钮的方法
2016/12/27 Javascript
利用ES6语法重构React组件详解
2017/03/02 Javascript
vue 2.0项目中如何引入element-ui详解
2017/09/06 Javascript
利用Javascript获取选择文本所在的句子详解
2017/12/03 Javascript
Vue中render函数的使用方法
2018/01/31 Javascript
详解Vue-cli3.X使用px2rem遇到的问题
2019/08/09 Javascript
vue 在单页面应用里使用二级套嵌路由
2020/12/19 Vue.js
Python中使用第三方库xlutils来追加写入Excel文件示例
2015/04/05 Python
用python制作游戏外挂
2018/01/04 Python
python3 selenium 切换窗口的几种方法小结
2018/05/21 Python
用Python获取摄像头并实时控制人脸的实现示例
2019/07/11 Python
python程序 创建多线程过程详解
2019/09/23 Python
TensorFlow tensor的拼接实例
2020/01/19 Python
PyQt5高级界面控件之QTableWidget的具体使用方法
2020/02/23 Python
Pandas之read_csv()读取文件跳过报错行的解决
2020/04/21 Python
使用Python将图片转正方形的两种方法实例代码详解
2020/04/29 Python
Pandas实现一列数据分隔为两列
2020/05/18 Python
html5教你做炫酷的碎片式图片切换 (canvas)
2017/07/28 HTML / CSS
长曲棍球装备:Lacrosse Monkey
2020/12/02 全球购物
Strathberry苏贝瑞中国官网:西班牙高级工匠手工打造
2020/10/19 全球购物
应届毕业生应聘自荐信
2013/12/07 职场文书
企业委托书范本
2014/09/13 职场文书
作文批改评语
2014/12/25 职场文书
诚实守信主题班会
2015/08/13 职场文书
教你用Python+selenium搭建自动化测试环境
2021/06/18 Python
浅谈什么是SpringBoot异常处理自动配置的原理
2021/06/21 Java/Android