# Change Of Behavior Of A Function To Compute Multiple Numpy Arrays Mean

## 27 September 2019 - 1 answer

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)
``````

wich outputs just as expected :

[ 5 148 252]

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

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

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

bgr3 = button_image[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.

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[x]).astype(np.int32)

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

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

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

bgr_mean = [ 5 148 252]