要在my_image 的最后一个轴上取平均值,请使用
np.average(my_image, axis=-1)
如果my_image 的形状为(H, W, 3),则np.average(my_image, axis=-1) 将返回一个形状为(H, W) 的数组。
例如,
In [9]: my_image = np.arange(18).reshape((3,2,3))
In [10]: np.average(my_image, axis=-1)
Out[10]:
array([[ 1., 4.],
[ 7., 10.],
[ 13., 16.]])
没有axis=-1,np.average 对数组中的所有值取平均值。
In [11]: np.average(my_image)
Out[11]: 8.5
imshow 需要一个数组,而不是浮点数。这就是您收到“无效维度”错误的原因。
使用 matplotlib 将数组显示为灰度图像:
In [24]: arr = np.average(my_image, axis=-1)
In [25]: plt.imshow(arr, interpolation='nearest', cmap=plt.get_cmap('gray'))
Out[25]: <matplotlib.image.AxesImage at 0xa8f01cc>
In [26]: plt.show()
使用 PIL 制作灰度图像:
import Image
import numpy as np
my_image = np.linspace(0, 255, 300*200*3).reshape((300,200,3))
arr = np.average(my_image, axis=-1)
img = Image.fromarray(arr.astype('uint8'))
img.save('/tmp/out.png')
请注意,除了取平均值之外,还有其他方法可以将 RGB 图像转换为灰度图像。例如,亮度由
定义
0.21 R + 0.72 G + 0.07 B
在实践中tends to produce a better result。