0

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?

  • 1
    What is the shape of the array? `imgarray[:, 0]` looks like you're taking the first column, not the first channel. – Brian61354270 Mar 24 '23 at 20:45
  • Do note that `len(reds) != reds.size` when `reds` is a multidimensional array. It seems you're summing the RGB values of the first column, and then dividing by the number of rows. – Brian61354270 Mar 24 '23 at 20:47

1 Answers1

2

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
Daweo
  • 31,313
  • 3
  • 12
  • 25