CPU版
pip install rembg
GPU版
pip install rembg[gpu]
批量去除文件夹内的图片的背景
from rembg import remove
import os
# Directory containing images to process
input_dir = ''
# Directory to save processed images
output_dir = ''
# Create the output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# List all files in the input directory
for filename in os.listdir(input_dir):
# Construct full file path
input_path = os.path.join(input_dir, filename)
# Check if the file is an image (add or modify extensions as needed)
if input_path.lower().endswith(('.png', '.jpg')):
# Construct the full output path
output_path = os.path.join(output_dir, filename)
# Process the image
with open(input_path, 'rb') as i:
with open(output_path, 'wb') as o:
input_data = i.read()
output = remove(input_data)
o.write(output)
print(f'Processed {filename}')