在白色背景上将透明 PNG 保存为 JPEG

2024-04-26

假设我有一张 BGRA 图像numpy数组看起来非常像这样:

[[[233 228 230   128]
  [233 228 230   128]
  [233 228 230   0]
  ...
  [164 160 159   65]
  [199 197 196   65]
  [255 255 254   120]]

这看起来非常简单 - 三个颜色通道 + 一个控制像素透明度的 Alpha。将 numpy 数组保存为 PNG 格式会产生应有的半透明图像。

然而,当将其另存为 JPEG 时,Alpha 通道会被完全丢弃,并且所有像素都完全不透明。

由于 JPEG 不支持 alpha 透明度,我希望将我的半透明图像(上面的 numpy 数组)保存在白色背景上。这样,像素看起来仍然是半透明的。

如何将半透明的 numpy 数组叠加在全白色背景上?我主要使用 numpy 和 OpenCV。


我认为您更多地寻找分级的 alpha 混合,而不是弗雷德的答案很好地演示的更简单的 alpha 阈值。

为了测试目的,我制作了一个中间带有 alpha 渐变的示例图像。这里它是一个普通图像,并合成在棋盘上以显示透明度,就像 Photoshop 所做的那样:

要进行 Alpha 混合,请使用以下公式:

result = alpha * Foreground + (1-alpha)*Background

其中值都是在 0..1 范围内缩放的浮点数


混合黑色和白色背景的代码如下:

#!/usr/bin/env python3

import cv2
import numpy as np

# Load image, including gradient alpha layer
im = cv2.imread('GradientAlpha.png', cv2.IMREAD_UNCHANGED)

# Separate BGR channels from A, make everything float in range 0..1
BGR = im[...,0:3].astype(np.float)/255
A   = im[...,3].astype(np.float)/255

# First, composite image over black background using:
# result = alpha * Foreground + (1-alpha)*Background
bg  = np.zeros_like(BGR).astype(np.float)     # black background
fg  = A[...,np.newaxis]*BGR                   # new alpha-scaled foreground
bg = (1-A[...,np.newaxis])*bg                 # new alpha-scaled background
res = cv2.add(fg, bg)                         # sum of the parts
res = (res*255).astype(np.uint8)              # scaled back up
cv2.imwrite('OverBlack.png', res)

# Now, composite image over white background
bg  = np.zeros_like(BGR).astype(np.float)+1   # white background
fg  = A[...,np.newaxis]*BGR                   # new alpha-scaled foreground
bg = (1-A[...,np.newaxis])*bg                 # new alpha-scaled background
res = cv2.add(fg, bg)                         # sum of the parts
res = (res*255).astype(np.uint8)              # scaled back up
cv2.imwrite('OverWhite.png', res)

这就给出了黑色:

这是白色的:

Keywords:图像处理、Python、OpenCV、alpha、alpha 混合、alpha 合成、叠加。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在白色背景上将透明 PNG 保存为 JPEG 的相关文章

随机推荐