Image Arithmetic Using OpenCV | Set-1 (addition and subtraction)



Arithmetic operations such as addition, subtraction, and bitwise operations (AND, OR, NOT, XOR) can be applied to input images. These operations can be useful for improving the properties of the input images. Image arithmetic is important for analyzing the properties of the input image. Driven images can optionally be used as an enhanced input image, and much more operations can be applied to the image to lighten, threshold, expand, etc.

Add an image:

We can add two images using the cv2.add () function. This directly adds image pixels to two images.

  Syntax:  cv2.add (img1, img2) 

But adding pixels is not ideal. So we are using cv2.addweighted () . Remember that both images must be the same size and depth.

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

Images used as input:

Input image1:

Input image2:

Below is the code:

# Python illustration program
# arithmetic operation
# adding two images

 
# organizing imports

import cv2 

import numpy as np 

 
# specifies the path to the input images and
# images are loaded using the imread command

image1 = cv2. imread ( `input1.jpg`

image2 = cv2.imread ( `input2.jpg` )

 
# cv2. addWeighted is applied over
# image input with parameters applied

weightedSum = cv2.addWeighted (image1, 0.5 , image2, 0.4 , 0 )

 
# window with displayed image
# weighted sum

cv2.imshow ( `Weighted Image` , weightedSum)

  
# Unallocate any associated memory usage

if cv2.waitKey ( 0 ) & amp;  0xff = = 27

cv2.destroyAllWindows () 

Output:

Image subtraction :

Like addition, we can subtract the pixel values ​​in two images and combine them using cv2.subtract () . Images must be the same size and depth.

  Syntax:  cv2.subtract (src1, src2) 

Images used as input:

Input image1:

Input image2:

Below is the code:

# Python illustration program
# arithmetic operation
# subtracting pixels of two images

 
# organization of import  

import cv2 

import numpy as np 

 
# specifies the path to the input images and
# images are loaded using the imread command

image1 = cv2.imread ( `input1.jpg`

image2 = cv2.imread ( `input2.jpg` )

 
# cv2.subtract is applied over
# image input from applied parameters

sub = cv2.subtract (image1, image2)

 
# window with the displayed image
# with the subtracted image

cv2.imshow ( `Subtracted Image` , sub)

  
# Deselect any associated memory usage

if cv2.waitKey ( 0 ) & amp;  0xff = = 27

cv2.destroyAllWindows () 

Output: