使用 OpenCV 对图像进行算术运算Set-1(加法和减法)
可以将加法、减法和按位运算(AND、OR、NOT、XOR)等算术运算应用于输入图像。这些操作有助于增强输入图像的属性。图像算法对于分析输入图像属性很重要。运算后的图像可以进一步用作增强的输入图像,并且可以应用更多的操作来对图像进行澄清、阈值化、膨胀等。
添加图像:
我们可以使用函数cv2.add()添加两个图像。这直接将两个图像中的图像像素相加。
Syntax: cv2.add(img1, img2)
但是添加像素并不是一个理想的情况。所以,我们使用 cv2.addweighted()。请记住,两个图像应该具有相同的大小和深度。
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
用作输入的图像:
输入图像1:
输入图像2:
下面是代码:
Python3
# Python program to illustrate
# arithmetic operation of
# addition of two images
# organizing imports
import cv2
import numpy as np
# path to input images are specified and
# images are loaded with imread command
image1 = cv2.imread('input1.jpg')
image2 = cv2.imread('input2.jpg')
# cv2.addWeighted is applied over the
# image inputs with applied parameters
weightedSum = cv2.addWeighted(image1, 0.5, image2, 0.4, 0)
# the window showing output image
# with the weighted sum
cv2.imshow('Weighted Image', weightedSum)
# De-allocate any associated memory usage
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
Python3
# Python program to illustrate
# arithmetic operation of
# subtraction of pixels of two images
# organizing imports
import cv2
import numpy as np
# path to input images are specified and
# images are loaded with imread command
image1 = cv2.imread('input1.jpg')
image2 = cv2.imread('input2.jpg')
# cv2.subtract is applied over the
# image inputs with applied parameters
sub = cv2.subtract(image1, image2)
# the window showing output image
# with the subtracted image
cv2.imshow('Subtracted Image', sub)
# De-allocate any associated memory usage
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
输出:
图像减法:
就像加法一样,我们可以将两个图像中的像素值相减并在 cv2.subtract() 的帮助下合并它们。图像应具有相同的大小和深度。
Syntax: cv2.subtract(src1, src2)
用作输入的图像:
输入图像1:
输入图像2:
下面是代码:
Python3
# Python program to illustrate
# arithmetic operation of
# subtraction of pixels of two images
# organizing imports
import cv2
import numpy as np
# path to input images are specified and
# images are loaded with imread command
image1 = cv2.imread('input1.jpg')
image2 = cv2.imread('input2.jpg')
# cv2.subtract is applied over the
# image inputs with applied parameters
sub = cv2.subtract(image1, image2)
# the window showing output image
# with the subtracted image
cv2.imshow('Subtracted Image', sub)
# De-allocate any associated memory usage
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
输出: