Arithmetic Operations
We can perform various arithmetic operations on images using OpenCV. In this tutorial, we will learn about how to perform arithmetic operations like - addition and subtraction on images.
Addition of Image
In OpenCV, the cv2.add() function is used to perform the addition of two images. This function takes two images as input and outputs an image that is the result of the operation. The images must have the same size and type. Let’s understand this with some practical work.
Example:
Input 1
Input 2
Code:
import cv2
image1 = cv2.imread('sum_a.jpg',1)
image2 = cv2.imread('sum_b.jpg',1)
image = cv2.add(image1, image2)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Here, first we imported cv2 and then we used cv2.imread to read both images of the given path. Then we used cv2.add to add pixels of both images. At last we used cv2.imshow function to display the final result.
Result:
We can also use cv2.addWeighted() function to perform a weighted sum of two images, where we can control the weight of each image.
Example:
import cv2
image1 = cv2.imread('sum_a.jpg',1)
image2 = cv2.imread('sum_b.jpg',1)
image = cv2.addWeighted(image1, 0.2 ,image2, 0.4, 0)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Result
Subtraction of Image
In OpenCV, just like the addition operation we can use cv2.subtract() function to subtract the second image from the first image of same size and type.
Example:
Input 1
Input 2
Code:
import cv2
image1 = cv2.imread('opencv.jpg',1)
image2 = cv2.imread('sum_b.jpg',1)
image = cv2.subtract(image1 ,image2)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Here, first we imported cv2 and then we used cv2.imread to read both images of the given path. Then we used cv2.subtract to subtract pixels of the second image from the first image. At last we used cv2.imshow function to display the final result.
Result: