在Python中有一些定制库,您可以使用它们来删除图像中的背景.

下面使用的rembg库就是一个例子:

from rembg import remove
from PIL import Image

input_path = 'input.png'
output_path = 'output.png'

input = Image.open(input_path)
output = remove(input)
output.save(output_path)

我的项目是比较图像的背景.

是否可以将删除的背景也保存为PNG?

推荐答案

背景在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:
enter image description here

Output:
enter image description here

Negated alpha:
enter image description here


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.

Python-3.x相关问答推荐

根据收件箱内部的值以行降序的特定顺序重新排序列

为什么我必须在绘制椭圆时代码等于两次?''

只有在Chrome尚未打开的情况下,打开Chrome后,PySimpleGUI窗口才会崩溃

Python gpsd客户端

按小时和日期对Pandas 数据帧进行分组

While循环不停止地等待,直到时间.睡眠结束

Django 3.2/Django-cms 3.11:查找错误:型号帐户.客户用户未注册

文件名中的文件打开和撇号

visual studio代码窗口中未激活虚拟环境11

Python中提取每个组/ID所属特定列中的自然数

txt 文件与不同的分隔符到整数列表

Jupyter Notebook 拒绝打印一些字符串

如何准确测定cv2的结果.在BW/黑白图像中查找对象?

聚合(aggregate)为最多包含两个元素的列表

导入 python 模块而不实际执行它

将 args、kwargs 传递给 run_in_executor

如何等待 create_task() 创建的任务完成?

为现有项目创建virtualenv

没有名为urlparse的模块,但我没有使用 urlparse

Windows 下 Python 3.x 的 OpenCV