Arithmetic Operations Using OpenCV | python



We can perform various arithmetic operations on images such as addition, subtraction, etc. This is possible because images are actually stored as arrays (3-D for RGB images and 1-D for grayscale images ).

Importance of image arithmetic:

  • Image Blending: Image Blending is used to blend images when the images are multiplied with different weights and stacked together to create a blending effect.
  • WaterMarking: It is also based on the principle of adding a very original image to the original image.
  • Detecting changes in an image. Image subtraction can help detect changes in two images and even out uneven areas of an image, for example, process half of an image that has a shadow.

Code for adding images —

import   cv2

import matplotlib.pyplot as plt % matplotlib inline

# matplotlib can be used to plot images as a subplot

  

first_img = cv2 .imread ( " C: //gfg//image_processing//players.jpg " )

second_img = cv2 .imread ( " C: //gfg//image_processing//tomatoes.jpg " )

  

print (first_img.shape)

print (second_img.shape)

 
# we need to resize as they differ in shape

dim = ( 544 , 363 )

resized_second_img = cv2.resize (second_img, dim, interpolation = cv2.INTER_AREA)

print ( "shape after resizing" , resized_second_img.shape)

  

added_img = cv2 .add (first_img, resized_second_img)

 

cv2.imshow ( "first_img" , first_img)

cv2 .waitKey ( 0 )

cv2. imshow ( "second_img" , resized_second_img)

cv2.waitKey ( 0 )

cv2.imshow ( "Added image" , added_img)

cv2.waitKey ( 0 )

  
cv2.destroyAllWindows ( )

Output:
(363, 544, 3)
(500, 753, 3)
shape after resizing (363, 544, 3)

Code for subtracting an image —

import   cv2

import matplotlib.pyplot as plt % matplotlib inline

 

 

first_img = cv2.imread ( " C: //gfg//image_processing//players.jpg " )

second_img = cv2.imread ( " C: //gfg//image_processing//tomatoes.jpg " )

  

print (first_img.shape)

print (second_img.shape)

 
# we need to resize as they differ in shape

dim = ( 544 , 363 )

resized_second_img = cv2.resize (second_img, dim, interpolation = cv2.INTER_ AREA)

print ( "shape after resizing " , resized_second_img.shape)

  

subtracted = cv2.subtract (first_img, resized_second_img)

cv2.imshow ( "first_img" , first_img)

cv2.waitKey ( 0 )

cv2.imshow ( "second_img" , resized_second_img)

cv2.waitKey ( 0 )

cv2.imshow ( "subtracted image" , subtracted)

cv2.waitKey ( 0 )

  
cv2.destroyAllWindows ()

Output:
(363, 544, 3)
(500, 753, 3)
form after change size (363, 544, 3)