Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

np.sum gives a value that is higher than possible

I am trying to find the average red value of pixels in an image. The code I have written is as follows:

path = "C:\\Users\\Ariana\\Pictures\\img.jpg"
img = PIL.Image.open(path)
imgarray = np.array(img)
reds = imgarray[:, 0]
avered = np.sum(reds)/len(reds)
print(avered)

The output should be at most 255 because this is the highest pixel value it can hold, however, the current output is 275, which should not be possible.

I tried specifying an axis while using np.sum, and I tried using the normal sum function, but both solutions output an array as an answer. Am I slicing the array incorrectly or using np.sum incorrectly?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You gets 2D array, but then divide by length of one axis rather than number of elements, consider following simple example

import numpy as np
arr = np.array([[255,127],[127,255]])
print(len(arr)) # 2
print(np.sum(arr) / len(arr)) # 382.0

to avoid this and reinventing wheel, you might use np.mean function

import numpy as np
arr = np.array([[255,127],[127,255]])
print(np.mean(arr)) # 191.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading