Arithmetic Operations on Images using OpenCV¶
Arithmetic Operations like Addition, Subtraction, and Bitwise Operations(AND, OR, NOT, XOR) can be applied to the input images
- Addition
- Subtraction
Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are:
- Bitwise AND
- Bitwise OR
- Bitwise XOR
- Bitwise NOT
1. Addition¶
- Syntax: cv2.add(img1, img2)
But adding the pixels is not an ideal situation. So, we use cv2.addweighted(). Remember, both images should be of equal size and depth.
Image 1¶

Image 2¶

import cv2
import numpy as np
image1 = cv2.imread('ocv3.jpg')
image2 = cv2.imread('ocv4.jpg')
weightedSum = cv2.add(image1,image2)
cv2.imshow('Weighted Image', weightedSum)
cv2.waitKey(0)
cv2.destroyAllWindows()
After Addition¶

Syntax: cv2.addWeighted(img1, wt1, img2, wt2, gammaValue)
Parameters:
- img1: First Input Image array(Single-channel, 8-bit or floating-point)
- wt1: Weight of the first input image elements to be applied to the final image
- img2: Second Input Image array(Single-channel, 8-bit or floating-point)
- wt2: Weight of the second input image elements to be applied to the final image
- gammaValue: Measurement of light
import cv2
import numpy as np
image1 = cv2.imread('ocv3.jpg')
image2 = cv2.imread('ocv4.jpg')
weightedSum = cv2.addWeighted(image1, 0.5, image2, 0.5, 0)
cv2.imshow('Weighted Image', weightedSum)
cv2.waitKey(0)
cv2.destroyAllWindows()

2.Subtraction of Image:¶
Just like addition, we can subtract the pixel values in two images and merge them with the help of cv2.subtract(). The images should be of equal size and depth.
Syntax: cv2.subtract(image1, image2)
import cv2
import numpy as np
image1 = cv2.imread('ocv3.jpg')
image2 = cv2.imread('ocv4.jpg')
weightedSum = cv2.subtract(image1,image2)
cv2.imshow('Weighted Image', weightedSum)
cv2.waitKey(0)
cv2.destroyAllWindows()

Machine Learning Tutorials, Courses and Certifications