np.sum gives a value that is higher than possible

Question:

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?

Asked By: Ariana DeLuca

||

Answers:

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
Answered By: Daweo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.