Python Opencv实践 - 图像混合

复制代码
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])
相关推荐
用户8356290780513 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780515 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠10 小时前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz31011 小时前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫11 小时前
python环境|conda安装和使用(2)
后端·python
程序员龙叔1 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780511 天前
使用 Python 操作 Word 内容控件
后端·python
LDR0061 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术1 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript