Opencv arithmetic operation

1. Addition of images

You can add two images using OpenCV's cv.add() function, or you can simply add two images through numpy operations like res = img1 + img2. Both images should be of the same size and type, or the second image can be a scalar value.

Note: There is a difference between OpenCV addition and Numpy addition. OpenCV 's addition is a saturating operation, while Numpy 's addition is a modulo operation.

Refer to the following code:

x = np.uint8([250])
y = np.uint8([10])
print( cv.add(x,y) ) # 250+10 = 260 => 255[[255]]
print( x+y )          # 250+10 = 260 % 256 = 4[4]

This difference becomes more apparent when you add the two images. OpenCV results are a bit better. So we try to use the functions in OpenCV.

We will have the following two images:

 

code:

import numpy as np

import cv2 as cv

import matplotlib.pyplot as plt

# 1 读取图像

img1 = cv.imread("view.jpg")

img2 = cv.imread("rain.jpg")

# 2 加法操作

img3 = cv.add(img1,img2) # cv中的加法

img4 = img1+img2 # 直接相加

# 3 图像显示

fig,axes=plt.subplots(nrows=1,ncols=2,figsize=(10,8),dpi=100)

axes[0].imshow(img3[:,:,::-1])

axes[0].set_title("cv中的加法")

axes[1].imshow(img4[:,:,::-1])

axes[1].set_title("直接相加")

plt.show()

The result looks like this:,

 

2. Blending of images

This is actually addition, but the difference is that the weights of the two images are different, which will give people a feeling of blending or transparency. The calculation formula for image blending is as follows:

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

By modifying the value of α (0 → 1), very cool blends can be achieved.

Now we blend the two images together. The weight of the first image is 0.7 and the weight of the second image is 0.3. The function cv2.addWeighted() can perform mixed operations on pictures according to the following formula.

dst = α⋅img1 + β⋅img2 + c

Here γ is taken as zero.

Refer to the following code:

import numpy as np

import cv2 as cv

import matplotlib.pyplot as plt

# 1 读取图像

img1 = cv.imread("view.jpg")

img2 = cv.imread("rain.jpg")

# 2 图像混合

img3 = cv.addWeighted(img1,0.7,img2,0.3,0)

# 3 图像显示

plt.figure(figsize=(8,8))

plt.imshow(img3[:,:,::-1])

plt.show()

The window will appear as shown below:

 

Summarize

Image addition: loading two images together

cv.add()

Image blending: blending two images in different proportions

cv.addweight()

Note: Both images are required to be the same size.

Guess you like

Origin blog.csdn.net/m0_62064241/article/details/126465568