1,rembg(去除背景-》蒙版)
import rembg
from PIL import Image, ImageOps
import numpy as np
# 打开图像
input_path = "./p_6258838.jpg"
input_image = Image.open(input_path)
# 移除背景,得到带有透明背景的图像
output_image = rembg.remove(input_image)
# 将 PIL 图像对象转换为 NumPy 数组,以便进一步处理
output_image_np = np.array(output_image)
# 检查是否有 alpha 通道(4通道图像:RGBA),并生成蒙版
if output_image_np.shape[2] == 4:
# 提取 alpha 通道,alpha 通道的值为 0 的部分为透明,255 为不透明
alpha_channel = output_image_np[:, :, 3]
# 转换为黑白蒙版,透明的部分设为黑色(0),不透明部分设为白色(255)
mask = np.where(alpha_channel > 0, 255, 0).astype(np.uint8)
# 将蒙版转换回 PIL.Image 对象
mask_image = Image.fromarray(mask, mode='L') # 'L' 表示灰度图像
# 显示或保存蒙版
mask_image.show() # 显示蒙版图像
# mask_image.save("mask_image.png") # 如果需要,可以保存蒙版图像
else:
print("图像没有 alpha 通道,可能不是去除背景后的透明图像。")
2,关于inpatint anything 和 background remove 问题