本文共 1279 字,大约阅读时间需要 4 分钟。
数据集的lmdb
将数据集转换成lmdb实际上就是一条条地将img和label的key-value形式写进lmdb中
img数据在lmdb中是以二进制形式存储的
遍历lmdb中的数据
import cv2import lmdbimport numpy as npenv = lmdb.open('./data/train/CVPR2016')txn = env.begin()for key, value in txn.cursor(): #遍历 print(key)# print(value)env.close()
从lmdb中读取图片
import cv2import lmdbimport numpy as npenv = 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中写入数据
import lmdbimage_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_bincache['label_000'] = labelwith 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()
转载地址:http://tgygf.baihongyu.com/