参考 caffe 将三通道或四通道图片转换为lmdb格式,将标签(单通道灰度图)转换为lmdb格式 http://blog.csdn.net/c_qianbo/article/details/53375476
代码语言:javascript复制import numpy as np
import sys
from PIL import Image
import lmdb
import random
import os
sys.path.append('/home/guest/caffe/python/')
import caffe
if __name__ == '__main__' :
train_list_file = '/home/guest/caffe/examples
/VOC2012ext/VOCdevkit/VOC2012/ImageSets/Segmentation/val.txt'
train_images_root = '/home/guest/caffe/examples
/VOC2012ext/VOCdevkit/VOC2012/JPEGImages/'
f = open(train_list_file, 'r')
trainlist = f.readlines()
f.close()
random.shuffle(trainlist)
# creating images lmdb
in_db = lmdb.open('/home/guest/caffe/VOC2012ext_val_img_lmdb',
map_size=int(1e12))
with in_db.begin(write=True) as in_txn :
for in_idx, in_ in enumerate(trainlist) :
fid = in_.strip() '.jpg'
fn = os.path.join(train_images_root, fid)
im = np.array(Image.open(fn))
Dtype = im.dtype
im = im[:,:,::-1]
im = Image.fromarray(im)
im = np.array(im, Dtype)
im = im.transpose((2, 0, 1))
im_dat = caffe.io.array_to_datum(im)
in_txn.put('{:0>10d}'.format(in_idx), im_dat.SerializeToString())
in_db.close()
# creating label lmdb
in_db = lmdb.open('/home/guest/caffe/VOC2012ext_val_label_lmdb',
map_size=int(1e12))
train_images_root = '/home/guest/caffe/examples
/VOC2012ext/VOCdevkit/VOC2012/SegmentationClass/'
with in_db.begin(write=True) as in_txn :
for in_idx, in_ in enumerate(trainlist) :
fid = in_.strip() '.png'
fn = os.path.join(train_images_root, fid)
Dtype = 'uint8'
L = np.array(Image.open(fn), Dtype)
Limg = Image.fromarray(L)
L = np.array(Limg,Dtype)
L = L.reshape(L.shape[0],L.shape[1],1)
L = L.transpose((2,0,1))
L_dat = caffe.io.array_to_datum(L)
in_txn.put('{:0>10d}'.format(in_idx),L_dat.SerializeToString())
in_db.close()