使用opencv在透明背景上覆盖另一个图像

时间:2019-01-07 06:58:30

标签: python opencv opencv3.0

我正在尝试使用opencv将图像放置在另一个图像之上。两个图像都有透明的背景。这是我正在尝试的code

s_img = cv2.imread("obama2.png", -1)
l_img = cv2.imread('obama.png',-1)
x_offset = 162
y_offset = 69

y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]

alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s

for c in range(0, 3):
    l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
                              alpha_l * l_img[y1:y2, x1:x2, c])
cv2.imwrite('final.png',l_img)

obama.png obama.png

obama2.png enter image description here

final.png enter image description here

我希望第二个obama2.png位于obama.png之上(类似于imagemagick / libvips中的复合函数)。

我该怎么做才能获得想要的图像

2 个答案:

答案 0 :(得分:0)

这给了我想要的解决方案,但如果可能的话,我会选择更好的解决方案

    s_img = cv2.imread("obama2.png", -1)
    l_img = cv2.imread('obama.png',-1)
    for i in range(0,s_img.shape[0]):
        for j in range(0,s_img.shape[1]):   
            if s_img[i][j][3]!=0:
                l_img[i+y_offset][j+x_offset][0:3] = s_img[i][j][0:3]
                l_img[i+y_offset][j+x_offset][3] = 255

    cv2.imwrite('final2.png',l_img)

编辑:看来我错过了一些基本的知识。我还必须在循环时考虑alpha通道,因为背景图像也具有透明度。

s_img = cv2.imread("obama2.png", -1)
l_img = cv2.imread('obama.png',-1)
x_offset = 162
y_offset = 69

y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]

alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s

for c in range(0, 4):
    l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
                              alpha_l * l_img[y1:y2, x1:x2, c])
cv2.imwrite('final.png',l_img)

答案 1 :(得分:0)

对不起,我不太了解OpenCV。但是我认为您可能已经忘记了将obama2图像的宽度减去放置位置的一半。偏移量是相对于obama2图像的左上角相对于obama图像的左上角的。您可能测量到了脸的中心,在奥巴马图像上大约为x = 162。

但是如果您可以使用Imagemagick,该过程将非常简单:

convert obama.png obama2.png -geometry +82-6 -compose over -composite result.png


enter image description here

-geometry参数仅定义obama2图像相对于obama图像左上角的偏移量。如果我在奥巴马图像中测量脸部中心,则大约x = 176。因此,我必须减去obama2的一半宽度,即x = 192/2 = 96。因此,偏移量将为x = 176-96 = 80。我将其调整为82,然后将y = -6设置为稍微向上移动。

如果您需要Python解决方案,则可以使用基于Imagemagick的Wand