使用 OpenCV 为 png 设置白色背景而不是透明度

新手上路,请多包涵

我也有一个 OpenCv 图像;

 opencvImage = cv2.cvtColor(numpy_image, cv2.COLOR_RGBA2BGRA)

然后使用以下代码片段,我想删除透明度并设置白色背景。

 source_img = cv2.cvtColor(opencvImage[:, :, :3], cv2.COLOR_BGRA2GRAY)
source_mask = opencvImage[:,:,3]  * (1 / 255.0)

background_mask = 1.0 - source_mask

bg_part = (background_color * (1 / 255.0)) * (background_mask)
source_part = (source_img * (1 / 255.0)) * (source_mask)

result_image = np.uint8(cv2.addWeighted(bg_part, 255.0, source_part, 255.0, 0.0))

实际上,我可以将背景设置为白色,但是,实际图像颜色也会发生变化。我相信 COLOR_BGRA2GRAY 方法会导致此问题。这就是为什么我尝试使用 IMREAD_UNCHANGED 方法,但出现此错误: 函数“cvtColor”中不支持的颜色转换代码

顺便说一句,我对任何解决方案都持开放态度,我只是分享我的代码——可能需要一个小的修复。

原文由 eknbrk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 749
2 个回答

这是一个基本脚本,它将用白色替换所有完全透明的像素,然后删除 alpha 通道。

 import cv2
#load image with alpha channel.  use IMREAD_UNCHANGED to ensure loading of alpha channel
image = cv2.imread('your image', cv2.IMREAD_UNCHANGED)

#make mask of where the transparent bits are
trans_mask = image[:,:,3] == 0

#replace areas of transparency with white and not transparent
image[trans_mask] = [255, 255, 255, 255]

#new image without alpha channel...
new_img = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)

原文由 user1269942 发布,翻译遵循 CC BY-SA 4.0 许可协议

以前的所有答案都使用二值化,但掩码可以是非二进制的。在这种情况下,您可以使用带有白色背景的 alpha 混合

def alpha_blend_with_mask(foreground, background, mask): # modified func from link
    # Convert uint8 to float
    foreground = foreground.astype(float)
    background = background.astype(float)

    # Normalize the mask mask to keep intensity between 0 and 1
    mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
    mask = mask.astype(float) / 255

    # Multiply the foreground with the mask matte
    foreground = cv2.multiply(mask, foreground)

    # Multiply the background with ( 1 - mask )
    background = cv2.multiply(1.0 - mask, background)

    # Add the masked foreground and background.
    return cv2.add(foreground, background).astype(np.uint8)

img_with_white_background = alpha_blend_with_mask(img[..., :3], np.ones_like(clip_img) * 255, img[..., 3])

原文由 vozman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题