Image addition and subtraction

Image addition and subtraction can be performed with the cv2.add() and cv2.subtract() functions, respectively. These functions sum/subtraction the per-element sum/subtract of two arrays. These function can also be used to sum/subtract an array and a scalar. For example, if we want to add 60 to all the pixels of the image, we first have to build the image to add to the original, using the following code:

M = np.ones(image.shape, dtype="uint8") * 60

Then, we perform the addition, using the following code:

added_image = cv2.add(image, M)

Another possibility is to create a scalar and add it to the original image. For example, if we want to add 110 to all the pixels of the image, we first have to build the scalar using the following code:

scalar = np.ones((1, 3), dtype="float") * 110

Then, we perform the addition using the following code:

added_image_2 = cv2.add(image, scalar)

In the case of subtraction, the procedure is the same, but instead, we call the cv2.subtract() function. The full code for this script can be seen in arithmetic.py. The output of this script can be seen in the following screenshot:

In the preceding screenshot, you can clearly see the effect of adding and subtracting a predefined value (computed in two different ways, but showing the same results). When we add a value, the image will be lighter, and when we subtract a value, it will be darker.