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]
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With