读取图片的两种方式
一. 采用load_img读取图片
from keras_preprocessing import image
import matplotlib.pyplot as plt
img_path = r'E:\python_work\data\cats_and_dogs_small\test\cats\cat.1700.jpg'
img = image.load_img(img_path, target_size=(150, 150)) #加载路径和resize
img_tensor = image.img_to_array(img)
print(img_tensor.shape) #150*150*3格式
#img_tensor = np.expand_dims(img_tensor, axis=0) #表示在0位置插入ndim
#print(img_tensor.shape)
img_tensor = img_tensor.reshape(1, img_tensor.shape[0], img_tensor.shape[1], img_tensor.shape[2])
print(img_tensor.shape)
img_tensor /= 255.
print(img_tensor)
plt.imshow(img_tensor[0]) #四维向量用三维形式显示
plt.show()
要注意的几点:
- 这是采用keras中的图像处理模块,image.img_to_array(img) 将图片处理为3D张量形式。
- 重构4D张量的方式用reshape或者np.expand_dim都可以
- 输出的时候要注意降维输出(4D-3D),还有输出前要/255,查看说这是因为图像处理后由uint8变为了float类型,所以要归一化输出。
二. 直接用opencv处理,方便一些
img_path = r'E:\python_work\data\cats_and_dogs_small\test\cats\cat.1700.jpg'
img_src = cv2.imread(img_path)
img_src = cv2.resize(img_src, (150, 150))
b,g,r = cv2.split(img_src)
img2 = cv2.merge([r,g,b])
img2 = img2.reshape(1, img2.shape[0], img2.shape[1], img2.shape[2])
print(img2.shape)
#img2 = img2 * (1. / 255)
plt.imshow(img2[0])
plt.show()
要注意的几点:
- RGB通道的转换,因为opencv采用bgr,否则颜色不对
2.不需要一定除255,直接就可以imshow
最后,这两种方式读取的图片有细微差别,可以试试看。