带OpenCV的图像alpha合成

2024-09-28 01:24:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想实施以下步骤:

这是我的代码:

import cv2
from skimage.io import *
import numpy as np

imA = cv2.imread('C.jpg')
kernel = np.ones((3, 3), np.uint8)
imA = cv2.cvtColor(imA, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(imA, 5, 255, cv2.THRESH_BINARY)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
imshow(opening)
show()
imF = cv2.imread('157969651.jpg')
imF = cv2.cvtColor(imF, cv2.COLOR_BGR2RGBA)

imB = cv2.imread('images.jpg')
imB = cv2.cvtColor(imB, cv2.COLOR_BGR2RGBA)

imF[:, :, 0] *= opening
imF[:, :, 1] *= opening
imF[:, :, 2] *= opening
imF[:, :, 3] *= opening

imB[:, :, 0] *= (1 - opening)
imB[:, :, 1] *= (1 - opening)
imB[:, :, 2] *= (1 - opening)
imB[:, :, 3] *= (1 - opening)

res = imF + imB

imshow(res)
show()

结果:

我不知道这密码有什么问题。有人能看出我的脚步有什么不对吗?在


Tags: importshownpmaskcv2kernelcolorjpg
2条回答

检查你的面罩在0-1范围内,而不是在0-255范围内。在

阿尔法不是一个通道,是一个面具。在

我的解决方案:

import cv2
import numpy as np

foreground = cv2.imread('foreground.jpg')
background = cv2.imread('background.jpg')
kernel = np.ones((5, 5), np.uint8)

foreground_gray = cv2.cvtColor(foreground, cv2.COLOR_BGR2GRAY)

ret, mask = cv2.threshold(foreground_gray, 240, 255, cv2.THRESH_BINARY)

opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

output = np.zeros(foreground.shape, dtype=foreground.dtype)

for i in range(3):
    output[:, :, i] = background[:, :, i] *(opening/255) + foreground[:, :, i] *(1-opening/255)

cv2.imshow("img", output)
cv2.waitKey(0)

前景.jpg

enter image description here

背景.jpg

enter image description here

输出:

enter image description here

相关问题 更多 >

    热门问题