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])
相关推荐
孟健6 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞8 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽11 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程15 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪15 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook16 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python