Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate mean color of image in numpy array?

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

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

A sample 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 have tried:

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

But that outputs:

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

What I want is just the single RGB average value:

[0.5  0.5  0.5]
like image 342
dranobob Avatar asked Nov 20 '16 03:11

dranobob


People also ask

How do you find the average color of an image in Python?

Use the average() Function of NumPy to Find the Average Color of Images in Python. In mathematics, we can find the average of a vector by dividing the sum of all the elements in the vector by the total number of elements.

How do you find the mean of an image in Python?

mean: simply divide the sum of pixel values by the total count - number of pixels in the dataset computed as len(df) * image_size * image_size.

How do you find the average RGB of an image?

The typical approach to averaging RGB colors is to add up all the red, green, and blue values, and divide each by the number of pixels to get the components of the final color. There's a better way! Instead of summing up the components of the RGB color, sum their squares instead.


1 Answers

You're taking the mean along only one axis, whereas you need to take the mean along two axes: the height and the width of the image.

Try this:

>>> 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 the docs will tell you, you can specify a tuple for the axis parameter, specifying the axes over which you want the mean to be taken.

like image 152
Praveen Avatar answered Oct 09 '22 04:10

Praveen