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)
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[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.
Answer
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]
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module