Bounded sum or difference of arrays in numpy

I want to add or subtract two arrays in numpy, but the result should be limited to each element. If I restrict the type (i.e. Uint8), any amount of exeeding will overflow (i.e. start from zero again), and any difference in feed is downstream (i.e. start at 255 again). This is not what I want, i.e. I want to stop at 0/255 (in my example).

Is there a way to do this without accessing every element?

Thanks in advance.

+3


source to share


2 answers


you can use a mask

Example: adding does not exceed 255:

import numpy as np
# create exaple data where sum exceeds 255
a = np.arange(118,130,dtype = np.uint8)
b = a.copy()
res = np.add(a,b, dtype = np.uint16);
mask = res > 255
res[mask] = 255
res = np.uint8(res)

      



Results:

>>> print a
array([118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129], dtype=uint8)
>>> print b
array([118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129], dtype=uint8)
>>> print mask
array([False, False, False, False, False, False, False, False, False, False, True, True], dtype=bool)
>>> print res
array([236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 255, 255], dtype=uint8)

      

The mask only works correctly as a numpy array. Otherwise, extended indexing will return a view, not a copy, see SciPy / NumPy documentation.

+2


source


You can work with OpenCV if you have a cv2 library:

import cv2  
import numpy as np  

x=np.uint8([250])  
y=np.uint8([10])  
print cv2.add(x,y)  #250+ 10 =260=>255  

      



Answer:

[[255]] 

      

0


source







All Articles