dranobob
dranobob

Reputation: 836

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]

Upvotes: 23

Views: 43815

Answers (1)

Praveen
Praveen

Reputation: 7222

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.

Upvotes: 48

Related Questions