python - 使用 python 库叠加图像

标签 python

我想使用 Python 库将一张图片动态地叠加在另一张图片上,并且想知道哪一个会易于使用。

感谢您的帮助!

最佳答案

如果您想叠加两个图像,只需使用 OpenCV 库即可。

[示例]

enter image description here

enter image description here 这是使用 OpenCV 叠加 image1 和 image2 的示例 python 代码

import cv2
import numpy as np

def overlay(image1, image2, x, y):
    image1_gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
    _, contours, _ = cv2.findContours(image1_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    image1_mask = np.zeros_like(image1)
    cv2.drawContours(image1_mask, contours, -1, (255,255,255), -1)
    idx = np.where(image1_mask == 255)
    image2[y+idx[0], x+idx[1], idx[2]] = image1[idx[0], idx[1], idx[2]]
    return image2

if __name__ == '__main__':
    grass_img = cv2.imread('grassland.jpg')
    horse_img = cv2.imread('horse.png')
    overlayed = overlay(horse_img, grass_img, 300, 300)
    cv2.imwrite('overlayed.png', overlayed)

结果图像被调整大小以减小其体积,但在上面的代码中,调整大小的代码被省略了。

结果:

enter image description here

更新!

这是使用图像的 alpha 值的代码,输出比以前更好。

思路来自overlay a smaller image on a larger image python OpenCv

def better_overlay(image1, image2, x, y):
    image1_alpha = image1[:, :, 3] / 255.0
    height, width = image1.shape[0], image1.shape[1]
    for c in range(3):
        image2[y:y+height, x:x+width, c] = image1_alpha * image1[:, :, c] + (1.0 - image1_alpha)* image2[y:y+height, x:x+width, c]
    return image2

结果:

enter image description here

关于python - 使用 python 库叠加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6974923/

相关文章:

python - IronPython:无法识别双关键字?

Python logging - 过滤所有记录器的日志消息

python - 如何判断一年是否为闰年?

python - 在 Django-imagekit Thumbnail 中停止自动旋转图像

python - 如何在cmake中更改SWIG生成的.py文件?

python - PyTorch 的 `no_grad` 函数在 TensorFlow/Keras 中的等价物是什么?

python - python 中的多处理 imap_unordered

javascript - 如何将 strip 自定义结帐 token 发布到 flask 后端

python - Python 中的单独数字/字母标记

python - 多线程工具