import numpy as np
from PIL import Image
import cv2
try: #防止因为一个erro就停止运行整个程序
im = Image.open(path) #image库打开图片
width, height = im.size #PIL库用im.size cv2用im.shape
rerio = 1200.0/ height #获取一个缩放比率,以height为基准
print (width,height)
im = im.resize((int(width*rerio),1200)) # 相应缩放width
img = cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2BGR) #用cv2打开
in_ = np.array(im, dtype=np.float32) #转numpy
in_ = in_[:, :, ::-1] #CV2读入的格式是BGR通过此行转换为RGB
in_ -= np.array((104.00698793, 116.66876762, 122.67891434)) #subtract mean 减去均值
in_ = in_.transpose((2, 0, 1)) # transpose to channel x height x width order 将通道数放在前面(对应caffe数据存储的格式)
#其他操作
except Exception as e: #防止所有的错误
print(str(e)) #打印错误
但是我不知道为什么要减去均值呢?in_ -= np.array((104.00698793, 116.66876762, 122.67891434))
似乎是这个原因:由于使用了ImageNet的预训练权重,因此需要在数据预处理过程减去ImageNet上的均值。
补充:
import cv2
im = cv2.imread('data/src/lena.jpg')
print(type(im))
# <class 'numpy.ndarray'>
print(im.shape)
print(type(im.shape))
# (225, 400, 3)
# <class 'tuple'>
shape的输出顺序:height,width,channel
from PIL import Image
im = Image.open('data/src/lena.jpg')
print(im.size)
print(type(im.size))
# (400, 225)
# <class 'tuple'>
w, h = im.size
print('width: ', w)
print('height:', h)
# width: 400
# height: 225
size的输出顺序:width,height