如何计算numpy数组中图像的平均颜色?

dra*_*bob 8 python numpy image-processing

我有一个已转换为numpy数组的RGB图像.我正在尝试使用numpy或scipy函数计算图像的平均RGB值.

RGB值表示为0.0 - 1.0的浮点,其中1.0 = 255.

样本2x2像素image_array:

[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
 [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]
Run Code Online (Sandbox Code Playgroud)

我试过了:

import numpy
numpy.mean(image_array, axis=0)`
Run Code Online (Sandbox Code Playgroud)

但是那个输出:

[[0.5  0.5  0.5]
 [0.5  0.5  0.5]]
Run Code Online (Sandbox Code Playgroud)

我想要的只是单个RGB平均值:

[0.5  0.5  0.5]
Run Code Online (Sandbox Code Playgroud)

Pra*_*een 20

您只沿一个轴取平均值,而您需要沿两个轴取平均值:图像的高度和宽度.

试试这个:

>>> image_array    
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 1.,  1.,  1.],
        [ 1.,  1.,  1.]]])
>>> np.mean(image_array, axis=(0, 1))
array([ 0.5,  0.5,  0.5])
Run Code Online (Sandbox Code Playgroud)

正如文档将告诉您的那样,您可以为axis参数指定元组,指定您希望获取平均值的轴.

  • 而已!我没有意识到你可以指定多个轴. (2认同)