📜  使用 OpenCV 进行算术运算 | Python

📅  最后修改于: 2022-05-13 01:55:27.416000             🧑  作者: Mango

使用 OpenCV 进行算术运算 | Python

先决条件:使用 OpenCV 对图像进行算术运算 |基本

我们可以对图像执行不同的算术运算,例如加法、减法等。这是可能的,因为图像实际上存储为数组(RGB 图像为 3 维,灰度图像为 1 维)。

图像算术运算的重要性:

  • 图像混合:图像的添加用于图像混合,其中图像与不同的权重相乘并加在一起以产生混合效果。
  • WaterMarking:也是基于在原始图像上添加极低权重图像的原理。
  • 检测图像的变化:图像减法可以帮助识别两个图像中的变化以及平整图像的不均匀部分,例如处理图像上有阴影的一半。

图像添加代码 –

import  cv2
import matplotlib.pyplot as plt % matplotlib inline
# matplotlib can be used to plot the images as 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()

输出:
(363, 544, 3)
(500, 753, 3)
调整大小后的形状 (363, 544, 3)
图像减法代码 -

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()

输出:
(363, 544, 3)
(500, 753, 3)
调整大小后的形状 (363, 544, 3)