数据集的lmdb
将数据集转换成lmdb实际上就是一条条地将img和label的key-value形式写进lmdb中
img数据在lmdb中是以二进制形式存储的
遍历lmdb中的数据
import cv2 import lmdb import numpy as np env = lmdb.open('./data/train/CVPR2016') txn = env.begin() for key, value in txn.cursor(): #遍历 print(key) print(value) env.close()
从lmdb中读取图片
import cv2 import lmdb import numpy as np env = lmdb.open('./data/train/CVPR2016') with env.begin(write=False) as txn: # 获取图像数据 image_bin = txn.get('image-000004358'.encode()) label = txn.get('label-000004358'.encode()).decode() # 解码 # 将二进制文件转为十进制文件(一维数组) image_buf = np.frombuffer(image_bin, dtype=np.uint8) # 将数据转换(解码)成图像格式 # cv2.IMREAD_GRAYSCALE为灰度图,cv2.IMREAD_COLOR为彩色图 img = cv2.imdecode(image_buf, cv2.IMREAD_COLOR) cv2.imwrite('show.jpg',img) print(label)
从lmdb中读取label
虽然直接print value就能看到label值了,但它是b'Angles' 形式的,这种形式也就是bytes 对象形式,要想转成字符串要加.decode
import cv2 import lmdb import numpy as np env = lmdb.open('./data/test/cute80_288') txn = env.begin() for key, value in txn.cursor(): #遍历 key = key.decode('utf-8') value = value.decode('utf-8') with open('ct80_crop/'+key+'.txt', 'w') as f: f.write(value) env.close()
向lmdb中写入数据
写入图片和label
import lmdb image_path = './4.jpg' label = 'cat' env = lmdb.open('lmdb_dir') cache = {} # 存储键值对 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()
if key == b"num-samples": txn.put(key, b"300") 或 txn.put(key, str(300).encode())
如果读取过程中报错
lmdb.MapFullError: mdb_put: MDB_MAP_FULL: Environment mapsize limit reached
env = lmdb.open('./data/train/CVPR2016',map_size=int(1e13))
lmdb数据库的读取与转换(二) —— 数据集操作
最新推荐文章于 2025-03-14 16:17:36 发布