【问题标题】:Compute the sum of the red, green and blue channels using Python使用 Python 计算红色、绿色和蓝色通道的总和
【发布时间】:2018-08-01 08:14:50
【问题描述】:

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

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

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

【问题讨论】:

  • 什么是img?你在用什么库?
  • @iamanigeeit 抱歉没有说清楚。我已经编辑了我的问题。

标签: python image-processing


【解决方案1】:

我找到了您所说的原始代码。 我猜是:

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),您将 axe 2 的值相加。

例如,如果img[50,50] == [10,10,10],您将拥有intensity[50,50] = 30

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      来自documentation

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

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

      【讨论】:

        【解决方案4】:

        图像从文件读入一个 numpy 数组。您可以通过阅读文章Numpy sum axis intuition(尤其是示例)来了解轴和数据操作的整个概念:

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

        在 2-d 数组中,它可能会令人困惑,但是当我们谈论 3-d、4-d、n-d 时,它是定义轴的更直接的方法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-28
          • 2016-09-22
          • 1970-01-01
          • 1970-01-01
          • 2014-08-26
          • 2017-11-28
          相关资源
          最近更新 更多