import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img_dog = cv.imread("../SampleImages/pomeranian.png", cv.IMREAD_COLOR)
plt.imshow(img_dog[:,:,::-1])
img_water = cv.imread("../SampleImages/waterdrop.jpg", cv.IMREAD_COLOR)
plt.imshow(img_water[:,:,::-1])
#相同大小尺寸的两幅图像混合
#g(x) = (1 - a)h(x) + af(x), a为0-1之间的值,h(x),f(x)表示两幅图像的像素值
#cv.addWeighted(src1, alpha, src2, beta, gamma, dst=None, dtype=None)
#参考资料:https://blog.csdn.net/LaoYuanPython/article/details/109143281
img_blended = cv.addWeighted(img_dog, 0.75, img_water, 0.25, 0)
plt.imshow(img_blended[:,:,::-1])
# 不同尺寸之间的两幅图像混合,自定义一个函数
# addWeightedSmallImgToLargeImg(largeImg,alpha,smallImg,beta,gamma=0.0,regionTopLeftPos=(0,0))
# 前五个参数和addWeighted一样,多了一个regionTopLeftPos参数用于指定小图在大图中左上角的位置
def addWeightedSmallImgToLargeImg(largeImg,alpha,smallImg,beta,gamma=0.0,regionTopLeftPos=(0,0)):
srcW, srcH = largeImg.shape[1::-1]
refW, refH = smallImg.shape[1::-1]
x,y = regionTopLeftPos
if (refW>srcW) or (refH>srcH):
#raise ValueError("img2's size must less than or equal to img1")
raise ValueError(f"img2's size {smallImg.shape[1::-1]} must less than or equal to img1's size {largeImg.shape[1::-1]}")
else:
if (x+refW)>srcW:
x = srcW-refW
if (y+refH)>srcH:
y = srcH-refH
destImg = np.array(largeImg)
tmpSrcImg = destImg[y:y+refH,x:x+refW]
tmpImg = cv.addWeighted(tmpSrcImg, alpha, smallImg, beta,gamma)
destImg[y:y + refH, x:x + refW] = tmpImg
return destImg
img_cat = cv.imread("../SampleImages/cat.jpg", cv.IMREAD_COLOR)
plt.imshow(img_cat[:,:,::-1])
img_blended = addWeightedSmallImgToLargeImg(img_cat, 0.65, img_dog, 0.35, 0, (100,300))
plt.imshow(img_blended[:,:,::-1])
Python Opencv实践 - 图像混合
亦枫Leonlew2023-08-13 13:29