LMDB的全称是Lightning Memory-Mapped Database(快如闪电的内存映射数据库),它的文件结构简单,包含一个数据文件和一个锁文件
- env = lmdb.open():创建 lmdb 环境
- txn = env.begin():建立事务
- txn.put(key, value):进行插入和修改
- txn.delete(key):进行删除
- txn.get(key):进行查询
- txn.cursor():进行遍历
- txn.commit():提交更改
- env.close():结束
1. 生成一个空的lmdb数据库文件
import lmdb
env=lmdb.open("../data/hjb",map_size=1099511627776)
env.close()
![](https://img-blog.csdnimg.cn/img_convert/869914e2e8373f87c9cdbcd57578b57d.png)
2. lmdb数据的添加,修改,查询和删除
import lmdb
env = lmdb.open("../data/hjb")
txn = env.begin(write=True)
#增
txn.put(key=str(1).encode(),value='hjb'.encode())
txn.put(key="hjb".encode(),value='zwy'.encode())
txn.put(key=str(3).encode(),value='sda'.encode())
#查
print(txn.get(str(3).encode()))
#删
txn.delete(str(1).encode())
print(txn.get(str(1).encode()))
#改
txn.put(key="hjb".encode(),value="yes".encode())
print(txn.get("hjb".encode()))
txn.commit()
#对LMDB的读写操作在事务中执行,需要使用 commit 方法提交待处理的事务。
#每次commit() 之后都要用 env.begin() 更新txn(得到最新的lmdb数据库)。
env.close()
b'sda'
None
b'yes'
3.cursor() 遍历数据库
遍历数据库中的所有记录,其返回一个可迭代对象,相当于关系数据库中的游标,每读取一次,游标下移一位。
import lmdb
env=lmdb.open("../data/hjb")
txn=env.begin(write=True)
for key,value in txn.cursor():
print(key,value)
txn.commit()
env.close()
b'3' b'sda'
b'hjb' b'yes'
4. 图片数据示例
在深度学习训练中,一般会把大量原始数据集转化为lmdb格式方便后续的网络训练,因此需要对该数据集进行lmdb格式转化
将图片和对应的文本标签放到lmdb数据库
import lmdb
image_path='D:/hjb.jpg'
label='hjb'
env=lmdb.open('../data/hjb')
cache={} #存储{key,value}
#读取图像文件的二进制格式数据bytes
with open(image_path,'rb') as f:
image_bin=f.read()
#用两个键值对表示一个数据样本
cache['image_000']=image_bin
cache['label_000']=label
with env.begin(write=True) as txn:
for k,v in cache.items():
if isinstance(v,bytes):
#图片类型为bytes
txn.put(k.encode(),v)
else:
#图片类型为str,转化为bytes
txn.put(k.encode(),v.encode())
env.close()
从lmdb数据库中读取图片数据
import cv2
import lmdb
import numpy as np
env=lmdb.open('../data/hjb')
with env.begin(write=False) as txn:
img_bin=txn.get('image_000'.encode())
label=txn.get('label_000'.encode()).decode()
#标签通过decode(),进行解码重新得到字符串格式
#将二进制文件转为十进制文件(一维数组)
image_buf=np.frombuffer(img_bin,dtype=np.uint8)
#将数据转换为图像格式,使用 cv2.imdecode() 将其转换为灰度图(二维数组)或者彩色图(三维数组)。
img=cv2.imdecode(image_buf,cv2.IMREAD_COLOR)
cv2.imshow('image',img)
cv2.waitKey(0)
![](https://img-blog.csdnimg.cn/img_convert/6b8b6902a246d72fa57214c6db147fab.png)