python - 如何使用 numpy 将 alpha channel (透明度)添加到背景(不是正面图像)

标签 python numpy opencv image-processing computer-vision

我有一个 RGB 图像,并在处理后识别图像中的一个对象(该对象是零和非零值)。该图像显示了我要删除的黑色背景。
我尝试了以下两种方法:

Method 1: 
    rgba_image = np.insert(
        rgb_image,
        3,   #position in the pixel value [ r, g, b, a <-index [3]  ]
        255, #change as per requirement  
        axis=2 #this is the depth where you are inserting this alpha channel into
    )

Method 2: 
    b, g, r = cv2.split(img_numpy)
    alpha = np.ones(b.shape, dtype=b.dtype) * 100 #creating a dummy alpha channel image.
    rgba_image = cv2.merge((b, g, r, alpha))
这两种方法实际上都改变了透明度(但整个图像)。我正在寻找的是具有透明背景,仅显示对象
您能否提一些建议?

最佳答案

@MarkSetchell 帮助我解决了这个问题。在我的情况下,还有一点是我有张量中的数据,所以下面的代码解决了这个问题:

rgb_numpy = (image * 255).byte().cpu().numpy()

after this point the background is black

mask_alpha = (mask * 255).byte().cpu().numpy()

rgba_numpy = np.dstack((rgb_numpy,mask_alpha))
在此之后,添加了 mask 层,它会自动突出显示检测到的对象的区域,其他一切都变得透明

关于python - 如何使用 numpy 将 alpha channel (透明度)添加到背景(不是正面图像),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63958938/

相关文章:

Pythonrequirements.txt 显示安装了哪个包?

python - 响应不为空时,scrapy xpath 返回空列表

python - 平均值、纳米平均值和警告 : Mean of empty slice

python - 创建张量的欧式距离矩阵

python - opencv python中cv2.NORM_L2和cv2.NORM_L1的区别

Python __getattribute__ 和方法的包装

python - for 循环中的百分比变化

python - pip 不安装模块

c++ - Qt+Opencv中导入Gstreamer视频

opencv - 什么是 OpenCV 中的 Debug 模式和 Release 模式?