背景在output
图像的Alpha(透明度通道)中标记为零.
We may extract the alpha channel, negate it (255 - alpha)
, and scale the input by the negated alpha.
We may have to divide by 255 for bringing alpha to range [0, 1] before scaling.
代码示例:
from rembg import remove
from PIL import Image
import numpy as np
input_path = 'animal-2.jpg'
output_path = 'output.png'
background_path = 'background.png'
input = Image.open(input_path)
output = remove(input)
input_rgb = np.array(input)[:, :, 0:3] # Convert PIL to NumPy (keep only RGB channels).
outout_rgba = np.array(output) # Convert PIL to NumPy.
alpha = outout_rgba[:, :, 3] # Extract alpha channel.
alpha3 = np.dstack((alpha, alpha, alpha)) # Convert to 3 channels
background_rgb = input_rgb.astype(np.float) * (1 - alpha3.astype(np.float)/255) # Multiply by 1-alpha
background_rgb = background_rgb.astype(np.uint8) # Convert back to uint8
background = Image.fromarray(background_rgb)
output.save(output_path)
background.save(background_path)
Input:
Output:
Negated alpha:
Note:
The above solution assumes that there may be some alpha values between 0 and 255 (some semi-transparent background pixels), and my be simplified if assumed there are only 0 and 255 values.