繁体   English   中英

使用Python计算红色,绿色和蓝色通道的总和

[英]Compute the sum of the red, green and blue channels using Python

我一直在用Python上在线课程,遇到了一些我无法解释的代码。 我正在尝试计算图像的红色,绿色和蓝色通道的总和,这样做的代码行是:

img = plt.imread('480px-Astronaut-EVA.jpg') intensity = img.sum(axis=2)

为什么使用axis=2求和所有三个通道的值? 我正在使用matplotlib库。

我找到了您正在谈论的原始代码。 我认为是:

import matplotlib.pyplot as plt

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

# Print the shape of the image
print(img.shape)  # Outputs : (480, 480, 3)

然后,它计算第三个通道上的强度总和。

记住轴是:0、1和2。

# 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)  # Output : (480, 480)

这意味着,对于每对位置(axe0_point,axe1_point),您将ax 2的值相加。

例如,如果img[50,50] == [10,10,10] ,则intensity[50,50] = 30

文档中

对于RGB图像,返回值为MxNx3。

这意味着图像以MxN像素阵列存储,每个像素具有3个元组(R,G,B值)。 img.sum(axis=2)表示将每个像素的第三个轴(RGB值)相加,返回一个MxN强度值数组。

axis = 2(第三轴)指示求和颜色分量的总和:

B = image[:,:,0]; G = image[:,:,1]; R = image[:,:,2]

图像从文件读入numpy数组。 通过阅读Numpy sum轴直觉 (尤其是示例),您可以了解轴和数据操作的完整概念:

理解numpy sum的“轴”的方法是折叠指定的轴。 因此,当它折叠轴0(行)时,它仅变成一行和一列的和。

在2-d数组中,这可能会造成混淆,但是当我们谈论3-d,4-d,nd时,这是定义轴的更直接的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM