caffeRoot=""
import sys
import os
sys.path.append(os.path.join(caffeRoot, 'python'))
import caffe
img_size=256
crop_size=224
mean_data=np.load(os.path.join(caffeRoot,'python/caffe/imagenet/ilsvrc_2012_mean.npy')).mean(1).mean(1)
transformer = caffe.io.Transformer({'data': (1,3,img_size,img_size)})
transformer.set_transpose('data', (2,0,1))
transformer.set_mean('data', mean_data)
transformer.set_raw_scale('data', 255)
transformer.set_channel_swap('data', (2,1,0))
def prepare_image(imfile, oversample=True):
img=caffe.io.load_image(imfile)
img=transformer.preprocess('data',img)
if oversample:
crops_data=np.zeros((10,3,crop_size,crop_size),np.float32)
indices = [0, img_size-crop_size]
n = 0
for i in indices:
for j in indices:
crops_data[n,:, :, :] = img[:,i:i+crop_size, j:j+crop_size]
crops_data[n+5,:, :, :] = crops_data[n,:, :, ::-1]
n = n + 1
center=indices[1]//2
crops_data[n,:, :, :] = img[:,center:center+crop_size, center:center+crop_size]
crops_data[n+5,:, :, :] = crops_data[n,:, :, ::-1]
else:
img=caffe.io.resize_image(img, (crop_size,crop_size))
crops_data=img[np.newaxis,:]
return crops_data
输入图片:
过采样(图片四个角+中心+水平翻转)输出: