首页 > 解决方案 > 输出截断( img.sum(axis=2)

问题描述

你能解释一下轴2部分吗?img.sum(轴=2)

RGB 输出是如何被截断的?谢谢

输出: (480, 480, 3) (480, 480)

# Load the image into an array: img
img = plt.imread('some_random_image.jpg')

# Print the shape of the image
print(img.shape)

# Compute the sum of the red, green and blue channels: intensity
intensity = img.sum(axis=2) 

# Print the shape of the intensity
print(intensity.shape)

# Display the intensity with a colormap of 'gray'
plt.imshow(intensity,cmap='gray')

# Add a colorbar
plt.colorbar()

# Hide the axes and show the figure
plt.axis('off')
plt.show()

标签: python

解决方案


我不太确定我理解你的问题,但这是我能说的:

sum(axis=2)表示您正在对数组的第二个元素的方向进行求和img.shape(等于 [480, 480, 3]

所以sum(axis=2)要总结 img[:, :, 0] + img[:, :, 1] + img[:, :, 2]

因此,您获得了一个形状数组 (480,480),其中每个元素都等于:

img[i, j] = img[i, j, 0] + img[i, j, 1] + img[i, j, 2]

您现在只有一个二维数组,因为默认情况下 np.sum 函数会减小数组的大小

如果要保留 3D 数组,请执行img.sum(axis=2, keepdims = True)


推荐阅读