python - 如何使用 numpy 将 alpha 通道(透明度)添加到背景(不是正面图像)
问题描述
我有一个 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))
在此之后,添加了遮罩层,它会自动突出显示检测到的对象的区域,其他一切都变得透明
推荐阅读
- azure - B1 层应用服务计划可以拥有多少个子域?
- python - 如何在二维数组中使用 scipy 最小化?
- jquery - 如何使用 jquery 隐藏或显示 bootstrap 4 折叠
- node.js - Angular 11 HttpClient Generic Observable 将服务值映射到一个类中
- c# - 使用 C# 的先到先服务 (FCFS) CPU 调度错误
- javascript - 如何将坐标数组格式化为不同的参考点
- python - slurm 在 bash 中获取工作 ID
- prolog - 用序言消除列表元素的连续重复
- excel - 用条件求时间差的公式
- flutter - 如何实现这张图片的下拉刷新和上拉加载更多功能?