Thursday , November 21 2024

Arithmetic Operations on Images using OpenCV

10 Arithmetic Operations on Images using OpenCV

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

  1. Addition
  2. Subtraction

Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are:

  1. Bitwise AND
  2. Bitwise OR
  3. Bitwise XOR
  4. 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

In [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
In [3]:
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)

In [4]:
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()

About Machine Learning

Check Also

Record Video From a Webcam using OpenCV

12 Record Video using OpenCV Record Video From a Webcam using OpenCV¶ cv2.VideoWriter( filename, fourcc, …

Leave a Reply

Your email address will not be published. Required fields are marked *