'Change of behavior of a function to compute multiple numpy arrays mean

I have three BGR color values (stored into numpy arrays) and I want to compute their mean value (of each element, as to have a numpy array looking like this : [meanB, meanG, meanR]).

It's a pretty simple task and I found this way to do it:

import numpy as np

bgr1 = np.array([6, 149, 254])
bgr2 = np.array([5, 146, 251])
bgr3 = np.array([5, 149, 251])

bgr_mean = ((bgr1 + bgr2 + bgr3) / 3).astype(int)

print(bgr_mean)

which outputs just as expected:

[ 5 148 252]

My problem is that when I implement this in my code, it does not give the same result at all, despite each elements value and type being the same. This code:

bgr1 = button_image[0][x]
print("bgr1 = " + str(bgr1))
print(type(bgr1))

bgr2 = button_image[0][x-1]
print("bgr2 = " + str(bgr2))

bgr3 = button_image[1][x+1]
print("bgr3 = " + str(bgr3))

bgr_mean = ((bgr1 + bgr2 + bgr3) / 3).astype(int)
print("bgr_mean = " + str(bgr_mean))

outputs:

bgr1 = [ 6 149 254]

class 'numpy.ndarray'

bgr2 = [ 5 146 251]

bgr3 = [ 5 149 251]

bgr_mean = [ 5 62 81]

Button_image is a numpy array BGR image, and x (int type) is the middle (x-axis, duh) of the image. My test script is in the same project as the other code, using Python 3.7.4 and the same numpy version (1.16.3)

It's my first question so I hope I wrote it right, thank you in advance if you have any idea of what's causing this.



Solution 1:[1]

So like the first comment said, array's dtype was the problem. Because i was fetching BGR values from a BGR image array, they inherited its dtype (uint8). The solution is simply to cast each bgr array to np.int32 dtype before calculating their mean :

bgr1 = (button_image[0][x]).astype(np.int32)

bgr2 = button_image[0][x-1].astype(np.int32)

bgr3 = button_image[1][x+1].astype(np.int32)

bgr_mean = ((bgr1 + bgr2 + bgr3) / 3).astype(int)
print("bgr_mean = " + str(bgr_mean))

bgr_mean = [ 5 148 252]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1