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])
相关推荐
咕白m62511 小时前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
SelectDB1 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵2 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li2 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸2 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田3 天前
Pydantic校验配置文件
python
hboot3 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi3 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化