Reputation: 52646
when i add two images in opencv, sum is limited to 255. (Both images are of uint8)
ie 175+100 is 255 in opencv.
but if we add it using numpy.add function, result is not a limited one.
ie 175+100 is 19 in numpy.
Question:
1) Why it happen so?
2) Is there a way for np.add to behave like cv2.add? ie limit sum to 255?
Thanks in advance.
Upvotes: 1
Views: 2712
Reputation: 46
NumPy uses "modulo" arithmetic on overflow rather than clipping. This is the behavior of add on uint8 integers in C. So, 175+100 % 256 = 19 which is the result you are getting.
To get this clipping behavior, you will need to do some work:
Here are a couple of ideas:
1) Use a higher precision:
im1 = im.astype('u2')
im2 = im.astype('u2')
tmp = im1 + im2
result = tmp.clip(0,255).astype('u1')
2) Make sure the result is >= both the input values:
tmp = im1 + im2
mask = (tmp < im1) | (tmp < im2)
tmp[mask] = 255
Upvotes: 3