Totemi1324
Totemi1324

Reputation: 518

Wrong values with np.mean()?

I'm quite new to programming (in Python) and so I don't understand what is going on here. I have an image (35x64) as a 3D-array and with np.mean(), I attempted to extract the mean of one color channel of one row:

print(np.mean(img[30][:][0]))

For comparison, I also wrote a for-loop to append the exact same values in a list and calculating the mean with that:

for i in range(64):
    img_list.append(img[30][i][0])
print(np.mean(img_list))

Now, for a strange reason, it gives different values:

First output: 117.1
Second output: 65.7

By looking at the list, I discovered that the second one is correct. Can somebody with more experience explain to me why this is exactly happening and how to fix that? I don't want to use the second, longer code chunk in my programs but am searching for a 1-line solution that gives a correct value.

Upvotes: 2

Views: 587

Answers (1)

Jean-Didier
Jean-Didier

Reputation: 1977

There's a subtle difference between img[30][:][0] and img[30,:,0] (the one you were expecting). Let's see with an example:

img = np.arange(35*64*3).reshape(35,64,3)
img[30][:][0]
# array([5760, 5761, 5762])
img[30,:,0]
# array([5760, 5763, ... 5946, 5949])

So you simply need to:

print(np.mean(img[30,:,0]))

(which is more efficient anyways).

Some details: in your original syntax, the [:] is actually just triggering a copy of the array:

xx = img[30]
yy = img[30][:]
print (xx is yy, xx.shape, yy.shape, np.all(xx==yy))
# False (64, 3) (64, 3) True # i.e. both array are equal 

So when you take img[30][:][0], you're actually getting the 3 colors of the first pixel of row 30.

Upvotes: 5

Related Questions