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 相关文章推荐
python3+PyQt5+Qt Designer实现堆叠窗口部件
Apr 20 Python
python自动登录12306并自动点击验证码完成登录的实现源代码
Apr 25 Python
修复 Django migration 时遇到的问题解决
Jun 14 Python
对python sklearn one-hot编码详解
Jul 10 Python
Python3匿名函数用法示例
Jul 25 Python
利用Python如何实现一个小说网站雏形
Nov 23 Python
pandas读取csv文件,分隔符参数sep的实例
Dec 12 Python
python基础梳理(一)(推荐)
Apr 06 Python
PyQt5的安装配置过程,将ui文件转为py文件后显示窗口的实例
Jun 19 Python
python 如何去除字符串头尾的多余符号
Nov 19 Python
python实现井字棋小游戏
Mar 04 Python
利用4行Python代码监测每一行程序的运行时间和空间消耗
Apr 22 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
火影忍者:这才是千手柱间和扉间的真正死因,角都就比较搞笑了!
2020/03/10 日漫
php中实现记住密码自动登录的代码
2011/03/02 PHP
PHP将两个关联数组合并函数提高函数效率
2014/03/18 PHP
PHP微信API接口类
2016/08/22 PHP
PHP中CheckBox多选框上传失败的代码写法
2017/02/13 PHP
PHP使用redis消息队列发布微博的方法示例
2017/06/22 PHP
jquery last-child 列表最后一项的样式
2010/01/22 Javascript
javascript getElementsByTagName
2011/01/31 Javascript
从面试题学习Javascript 面向对象(创建对象)
2012/03/30 Javascript
ExtJS DOM元素操作经验分享
2013/08/28 Javascript
深入理解JavaScript系列(36):设计模式之中介者模式详解
2015/03/04 Javascript
基于Bootstrap实现Material Design风格表单插件 附源码下载
2016/04/18 Javascript
使用Bootstrap打造特色进度条效果
2017/05/02 Javascript
angular6 利用 ngContentOutlet 实现组件位置交换(重排)
2018/11/02 Javascript
JS手写一个自定义Promise操作示例
2020/03/16 Javascript
Vue中函数防抖节流的理解及应用实现
2020/04/24 Javascript
[05:31]DOTA2英雄梦之声_第04期_光之守卫
2014/06/23 DOTA
Python时间戳与时间字符串互相转换实例代码
2013/11/28 Python
pandas 将list切分后存入DataFrame中的实例
2018/07/03 Python
python通过ffmgep从视频中抽帧的方法
2018/12/05 Python
Python正则匹配判断手机号是否合法的方法
2020/12/09 Python
PyQt5组件读取参数的实例
2019/06/25 Python
用Python徒手撸一个股票回测框架搭建【推荐】
2019/08/05 Python
使用PyTorch将文件夹下的图片分为训练集和验证集实例
2020/01/08 Python
python数据处理——对pandas进行数据变频或插值实例
2020/04/22 Python
Python3爬虫中Selenium的用法详解
2020/07/10 Python
玩转CSS3色彩
2010/01/16 HTML / CSS
一款纯css3实现的颜色渐变按钮的代码教程
2014/11/12 HTML / CSS
浅谈Html5页面打开app的一些思考
2020/03/30 HTML / CSS
屈臣氏越南官网:Watsons越南
2021/01/14 全球购物
仓库管理专业个人自我评价范文
2013/11/11 职场文书
大学生自我鉴定
2013/12/16 职场文书
领导干部保密承诺书
2014/08/30 职场文书
2014高三学生考试作弊检讨书
2014/12/14 职场文书
2019幼儿教师求职信(3篇)
2019/09/20 职场文书
HTML5 语义化标签(移动端必备)
2021/08/23 HTML / CSS