Python OpenCV - 用透明度覆盖图像

标签 python opencv transparency rgba

我想要实现的是将一张透明图像放在另一张图像之上。像这样:

enter image description here

我一直找不到任何解决方案,所以我决定逐个像素地计算结果颜色。那个对我有用,但是速度很慢。 我是 OpenCV 和 Python 的新手。

这是我的代码,我想到了:

import numpy as np
import cv2

img1 = cv2.imread("img1.png", -1)
img2 = cv2.imread("img2.png", -1) # this one has transparency
h, w, depth = img2.shape

result = np.zeros((h, w, 3), np.uint8)

for i in range(h):
    for j in range(w):
        color1 = img1[i, j]
        color2 = img2[i, j]
        alpha = color2[3] / 255.0
        new_color = [ (1 - alpha) * color1[0] + alpha * color2[0],
                      (1 - alpha) * color1[1] + alpha * color2[1],
                      (1 - alpha) * color1[2] + alpha * color2[2] ]
        result[i, j] = new_color

cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

还有其他方法吗?一些更快的方法,更快? 谢谢。

最佳答案

回答:

import numpy as np
import cv2

from time import time

img1 = cv2.imread("./test_image/rgb.jpg", -1)
img2 = cv2.imread("./test_image/rgba.png", -1) # this one has transparency
h, w, c = img2.shape

img1 = cv2.resize(img1, (w, h), interpolation = cv2.INTER_CUBIC)
result = np.zeros((h, w, 3), np.uint8)

#slow
st = time()
for i in range(h):
for j in range(w):
        color1 = img1[i, j]
        color2 = img2[i, j]
        alpha = color2[3] / 255.0
        new_color = [ (1 - alpha) * color1[0] + alpha * color2[0],
                      (1 - alpha) * color1[1] + alpha * color2[1],
                      (1 - alpha) * color1[2] + alpha * color2[2] ]
        result[i, j] = new_color
end = time() - st
print(end)

#fast
st = time()
alpha = img2[:, :, 3] / 255.0
result[:, :, 0] = (1. - alpha) * img1[:, :, 0] + alpha * img2[:, :, 0]
result[:, :, 1] = (1. - alpha) * img1[:, :, 1] + alpha * img2[:, :, 1]
result[:, :, 2] = (1. - alpha) * img1[:, :, 2] + alpha * img2[:, :, 2]
end = time() - st
print(end)

cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

关于Python OpenCV - 用透明度覆盖图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41508458/

相关文章:

c++ - 带有 FFMPEG 的 OpenCV RTP-Stream

android - 在OpenCV摄像机顶部渲染3D对象

reactjs - 在其他计算机上使用 native 模块执行 Electron 应用程序时出现 JS 错误

c# - 如何在 C# for iOS 中设置颜色在固定背景图像上的透明度级别?

transparency - 使用 Geopandas 绘制 shapefile 时,Alpha 透明度不均匀

python - 如何将列表列表更改为键、值?

python - 什么时候空格在 Python 中不重要?

PHP PNG 24 位透明透明

python - flask -NameError : name 'app' is not defined

python - 如何在 Amazon EMR 上的 Pig 中使用 Python 流 UDF