1

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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

2nd method is a lot slower than first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.