您的第一个代码块:import matplotlib.pyplot as plt
plt.imsave('image.png', image, format='png', cmap='gray')
这将图像保存为RGB,因为在向imsave提供RGB数据时忽略了cmap='gray'(请参见pyplot docs)。
您可以通过取三个波段的平均值,将数据转换为灰度,可以使用color.rgb2gray,也可以使用numpy:import numpy as np
from matplotlib import pyplot as plt
import cv2
img_rgb = np.random.rand(196,256,3)
print('RGB image shape:', img_rgb.shape)
img_gray = np.mean(img_rgb, axis=2)
print('Grayscale image shape:', img_gray.shape)
输出:RGB image shape: (196, 256, 3)
Grayscale image shape: (196, 256)
img_gray现在是正确的形状,但是如果使用plt.imsave保存它,它仍然会写入三个波段,每个像素的R==G==B。这是因为,我相信,一个PNG文件需要三(或四)个波段。警告:我不确定这一点:我希望得到纠正。plt.imsave('image_gray.png', img_gray, format='png')
new_img = cv2.imread('image_gray.png')
print('Loaded image shape:', new_img.shape)
输出:Loaded image shape: (196, 256, 3)
避免这种情况的一种方法是将图像保存为numpy文件,或者确实将一批图像保存为numpy文件:np.save('np_image.npy', img_gray)
new_np = np.load('np_image.npy')
print('new_np shape:', new_np.shape)
输出:new_np shape: (196, 256)
另一种方法是保存灰度png(使用imsave),但只读取第一个波段:finalimg = cv2.imread('image_gray.png',0)
print('finalimg image shape:', finalimg.shape)
输出:finalimg image shape: (196, 256)