python generates file instances in lmdb format

  • 2021-01-25 07:48:39
  • OfStack

lmdb format data set is needed for crnn training. The following is the code for python to generate lmdb data set. Note that 1 must be in the linux system, otherwise there will be problems when reading images.

#-*- coding:utf-8 -*-
import os
import lmdb# First, pip install This module 
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.
  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 =, map_size=8589934592)#1099511627776) The minimum amount of disk space required, previously was 1T "I changed it to 8g Otherwise, the disk space is reported as insufficient. This number is in bytes 
 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)
  with open(imagePath, 'r') as f:
   imageBin =
  if checkValid:
   if not checkImageIsValid(imageBin):
    print('%s is not a valid image' % imagePath)# Pay attention to 1 Need to linux Next, otherwise It's no longer available, and it will print this information 
  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 =
 text = text.strip()
 return text
if __name__ == '__main__':
 # lmdb  The output directory 
 outputPath = 'D:/ruanjianxiazai/tuxiangyangben/fengehou/train'# The training set and the validation set have to run through the program twice, generated in two batches 
 path = "D:/ruanjianxiazai/tuxiangyangben/fengehou/chenguang/*.jpg"# will txt with jpg Put everything in the same place 1 In a file. 
 imagePathList = glob.glob(path)
 print '------------',len(imagePathList),'------------'
 imgLabelLists = []
 for p in imagePathList:
   imgLabelLists.append((p, read_text(p.replace('.jpg', '.txt'))))
 # 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)

Related articles: