pycaffe之图像预处理

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) # mean pixel
transformer.set_raw_scale('data', 255)  # the reference model operates on images in [0,255] range instead of [0,1]
transformer.set_channel_swap('data', (2,1,0))  # the reference model has channels in BGR order instead of RGB

def prepare_image(imfile, oversample=True):

    img=caffe.io.load_image(imfile) # (H x W x C) ndarray
    img=transformer.preprocess('data',img) # (C x H x W) ndarray

    if oversample:
        # oversample (4 corners, center, and their x-axis flips)
        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

输入图片:
pycaffe之图像预处理_第1张图片

过采样(图片四个角+中心+水平翻转)输出:
pycaffe之图像预处理_第2张图片

你可能感兴趣的:(Python)