📜  在Python中使用 OpenCV 添加和混合图像

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

在Python中使用 OpenCV 添加和混合图像

当我们谈论图像时,我们知道它的所有关于二进制图像(0, 1)灰度图像(0-255)RGB 图像(255 255 255)的矩阵。所以图像的添加是添加两个矩阵的数量。在 OpenCV 中,我们有一个命令cv2.add()来添加图像。

下面是使用 OpenCV 添加两个图像的代码:

# Python program for adding
# images using OpenCV
  
# import OpenCV file
import cv2
  
# Read Image1
mountain = cv2.imread('F:\mountain.jpg', 1)
  
# Read image2
dog = cv2.imread('F:\dog.jpg', 1)
  
# Add the images
img = cv2.add(mountain, dog)
  
# Show the image
cv2.imshow('image', img)
  
# Wait for a key
cv2.waitKey(0)
  
# Distroy all the window open
cv2.distroyAllWindows()

但有时我们不想在图像中执行简单的加法,所以在这种情况下我们有混合。这也是图像添加,但对图像赋予不同的权重,以便给人一种混合或透明的感觉。图像根据以下等式添加:

g(x) = (1 - a)f(x) + af1(x)

通过从 0 -> 1 改变a ,您可以在一个图像到另一个图像之间执行一个很酷的过渡。这里拍摄了两张图像以混合在一起。第一张图像的权重为 0.3,第二张图像的权重为 0.7, cv2.addWeighted()对图像应用以下等式:

img = a . img1 + b . img 2 + y

这里y取为零。

下面是使用 OpenCV 混合图像的代码:

# Python program for blending of
# images using OpenCV
  
# import OpenCV file
import cv2
  
# Read Image1
mountain = cv2.imread('F:\mountain.jpg', 1)
  
# Read image2
dog = cv2.imread('F:\dog.jpg', 1)
  
# Blending the images with 0.3 and 0.7
img = cv2.addWeighted(mountain, 0.3, dog, 0.7, 0)
  
# Show the image
cv2.imshow('image', img)
  
# Wait for a key
cv2.waitKey(0)
  
# Distroy all the window open
cv2.distroyAllWindows()