我有一个 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/