How to calculate the average color of an image in a numpy array?

I have an RGB image that has been converted to a numpy array. I am trying to calculate the average RGB value of an image using the numpy or scipy functions.

RGB values ​​are represented as a floating point from 0.0 to 1.0, where 1.0 = 255.

Example 2x2 pixel 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]]] 

I tried:

 import numpy numpy.mean(image_array, axis=0)` 

But it gives out:

 [[0.5 0.5 0.5] [0.5 0.5 0.5]] 

I want only one average RGB value:

 [0.5 0.5 0.5] 
+5
source share
1 answer

You take the average value of only one axis, while you need to take the average value of two axes: the height and width of the image.

Try the following:

 >>> 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]) 

As docs will tell you, you can specify a tuple for t21> the <parameter, indicating the axes along which you want the average value to be accepted.

+11
source

Source: https://habr.com/ru/post/1260022/


All Articles