OpenCV(十):图像核心操作之为图像上的算术运算

    技术2022-07-17  93

    图像上的算术运算:加法 减法 位运算法

    函数:cv2.add()  cv2.addWeighted()

    一、图像加法

    可以使用函数 cv2.add() , 将两副图像进行加法运算;当然也可以直接使用 Numpy,例如:res = img1+img2。这里要求两幅图像的大小、类型必须一致,或者第二个图像可以使一个简单的标量值。

    注意:OpenCV中的加法和Numpy中的加法是不一样的,OpenCV中的加法是一种饱和操作,而Numpy的加法是一种模操作。

    例如:

    import cv2 import numpy as np x = np.uint8([250]) y = np.uint8([10]) print(cv2.add(x, y)) # 250+10 = 260 ==> 255 (饱和运算) ''' [[255]] ''' print(x + y) # 250+10 = 260 % 256 = 4 (模运算) ''' [4] '''

    建议:两种差距在对两副图像进行加法时会更加明显,OpenCV的结果会更好,尽量使用OpenCV中的函数。

    二、图像混合

    同样是加法,但是两幅图像的权重不同,这会给人一种混合或者透明的感觉,图像混合的计算公式如下:

    g(x) = (1-α)f0(x) + αf1(x)

    通过修改α的值(0->1),可以实现非常酷的操作;现在我们将两幅图像混合在一起,第一幅图像的权重是0.7,第二幅是0.3.

    函数:cv2.addWeighted(),可以按照下面的公式对图像进行混合操作;

    dst = α · img1 + β · img2 + γ   (这里 γ 的取值为 0)

    代码:

    dst = cv2.addWeighted(img1, 0.7, img2, 0.3, 0) cv2.imshow('dst', dst) cv2.waitKey(0) cv2.destroyAllWindows() ''' 这里 error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function 'cv::arithm_op' 错误很明显,要进行图像混合操作,需要两个图像的尺寸相同,我们需要使用 cv2.resize() 进行图像尺寸的修改 或者叫缩放 ''' img1 = cv2.imread('tree.jpg') img2 = cv2.imread('water.jpg') print(img1.shape) #(768, 1366, 3) 要注意,使用.shape输出的第一个值是height,第二个值是width。 print(img2.shape) #(500, 800, 3) # 直接使用cv2.resize函数对第一张图像的尺寸进行修改就好,其中第一个参数是待修改的图片,第二个参数是宽高,注意:第一个要填width,第二个是height,正好跟.shape的输出结果相反,不要搞混了。 img1 = cv2.resize(img1, (800, 500)) print(img1.shape) #(500, 800, 3) dst = cv2.addWeighted(img1, 0.7, img2, 0.3, 0) cv2.imshow('dst', dst) cv2.waitKey(0) cv2.destroyAllWindows()

    三、按位运算

    请听下回分解。。

    转载请注明转自:https://blog.csdn.net/Owen_goodman/article/details/107086623

    Processed: 0.018, SQL: 9