23

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]

1 Answer 1

48

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thats it! I didn't realize you could specify more than one axis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.