Suppose I have 2 uint8
arrays like this:
arr1 = np.array([50, 100, 150, 200, 250], dtype=np.uint8)
arr2 = np.array([50, 100, 150, 200, 250], dtype=np.uint8)
If I do array addition my intended result is:
[100 200 255 255 255]
i.e. when values get to the max value and then overflow, I'd like to keep the max value instead. Simply doing addition does not work due to this overflow concern:
import numpy as np
arr1 = np.array([50, 100, 150, 200, 250], dtype=np.uint8)
arr2 = np.array([50, 100, 150, 200, 250], dtype=np.uint8)
result = arr1 + arr2
print(result)
result (not as desired due to overflow for the last 3 numbers):
[100 200 44 144 244]
The easy around this is to convert to a larger datatype, so in this case uint16
, then convert back like so:
arr1 = np.array([50, 100, 150, 200, 250], dtype=np.uint8)
arr2 = np.array([50, 100, 150, 200, 250], dtype=np.uint8)
arr1 = arr1.astype(np.uint16)
arr2 = arr2.astype(np.uint16)
result = np.where(arr1 + arr2 > 255, 255, arr1 + arr2).astype(np.uint8)
This gives the intended result:
[100 200 255 255 255]
But my question is, is there a more efficient way to do this that does not involve converting to the next larger dtype?