Sherafati
Sherafati

Reputation: 216

What is the different between adding to images together using "+" and the add() method in Opencv in Python?

So imagine we have two images: img1 and img2. when adding these two together using + or cv2.add() we get different results. Why is that? How are they different?

img = img1 + img2
img = cv2.add(img1, img2)

Upvotes: 1

Views: 1782

Answers (2)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

Considering your img1 and img2 variables are of dtype == np.uint8: img1 + img2 is numpy addition, which is a modulo operation, whereas cv2.add(img1 + img2) is saturated operation.

np.uint8 is 8-bit unsigned integer (from 0 to 255), so if the resultant is out of bounds, then numpy and opencv handle that differently. For example:

>>> img1 = np.uint8([250])
>>> img2 = np.uint8([50])

# numpy
>>> img1 + img2
array([44], dtype=uint8)  # (250 + 50) % 256 = 44
# it takes the modulo of 256

# opencv
>>> cv2.add(img1, img2)
array([[255]], dtype=uint8)  # min(max(0, (250 + 50)), 255) = 255 or np.clip(300, 0, 255)
# it saturates to 255

For np.uint8 the range would be (0, 4294967295)

Upvotes: 2

Lior Cohen
Lior Cohen

Reputation: 5745

from the opencv documentation:

Image Addition You can add two images with the OpenCV function, cv.add(), or simply by the numpy operation res = img1 + img2. Both images should be of same depth and type, or the second image can just be a scalar value.

Note There is a difference between OpenCV addition and Numpy addition. OpenCV addition is a saturated operation while Numpy addition is a modulo operation. For example, consider the below sample:

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

This will be more visible when you add two images. Stick with OpenCV functions, because they will provide a better result.

Upvotes: 4

Related Questions