comfy_fm24_newgens/lib/remove_bg.py

72 lines
2.7 KiB
Python
Raw Normal View History

2024-12-13 12:06:05 +00:00
from rembg import remove
from PIL import Image
from tqdm import tqdm
2024-12-14 08:11:27 +00:00
import os
2024-12-13 16:43:45 +00:00
from concurrent.futures import ThreadPoolExecutor
2024-12-14 08:11:27 +00:00
import onnxruntime as ort
def process_images_in_batch(batch, directory, use_gpu):
2024-12-13 12:06:05 +00:00
"""
2024-12-14 08:11:27 +00:00
Process a batch of images: remove their backgrounds and save the results.
2024-12-13 16:43:45 +00:00
Args:
batch (list): List of filenames to process (without path or extension).
directory (str): Base directory to locate input files.
2024-12-14 15:49:36 +00:00
use_gpu (bool): Whether to enable GPU support.
2024-12-14 08:11:27 +00:00
2024-12-13 16:43:45 +00:00
Returns:
2024-12-14 08:11:27 +00:00
int: Number of images successfully processed in this batch.
2024-12-13 16:43:45 +00:00
"""
2024-12-14 08:11:27 +00:00
success_count = 0
for filename in batch:
input_path = os.path.join(directory, f"{filename}.png")
output_path = os.path.join(directory, f"{filename}.png")
2024-12-14 08:11:27 +00:00
try:
with Image.open(input_path) as img:
2024-12-14 15:49:36 +00:00
# Initialize ONNX session options with GPU support if required
session_options = ort.SessionOptions()
providers = ["CUDAExecutionProvider"] if use_gpu else ["CPUExecutionProvider"]
ort.set_default_logger_severity(3) # Suppress non-critical logging
# Initialize the rembg remove function with appropriate providers
output = remove(img, session_options=session_options, providers=providers)
2024-12-14 08:11:27 +00:00
output.save(output_path)
2024-12-14 08:11:27 +00:00
success_count += 1
except Exception as e:
print(f"Error processing {input_path}: {str(e)}")
2024-12-14 08:11:27 +00:00
return success_count
def remove_bg_from_file_list(directory, filenames, max_workers=2, batch_size=2, use_gpu=False):
2024-12-13 16:43:45 +00:00
"""
Process a list of specified filenames: remove their backgrounds and save the results.
2024-12-13 12:06:05 +00:00
Args:
directory (str): Path to the directory containing images.
filenames (list): List of filenames (without path or extension) to process.
2024-12-13 16:43:45 +00:00
max_workers (int): Maximum number of threads to use for parallel processing.
2024-12-14 08:11:27 +00:00
batch_size (int): Number of images to process per batch.
2024-12-14 15:49:36 +00:00
use_gpu (bool): Whether to enable GPU support.
2024-12-14 08:11:27 +00:00
2024-12-13 12:06:05 +00:00
Returns:
int: The number of images successfully processed.
"""
2024-12-14 08:11:27 +00:00
processed_count = 0
# Divide filenames into batches
batches = [filenames[i:i + batch_size] for i in range(0, len(filenames), batch_size)]
2024-12-14 08:11:27 +00:00
2024-12-13 16:43:45 +00:00
with ThreadPoolExecutor(max_workers=max_workers) as executor:
with tqdm(total=len(filenames), desc="Removing Backgrounds", unit="image") as pbar:
2024-12-14 15:49:36 +00:00
futures = {
executor.submit(process_images_in_batch, batch, directory, use_gpu): batch
2024-12-14 15:49:36 +00:00
for batch in batches
}
2024-12-13 16:43:45 +00:00
for future in futures:
2024-12-14 08:11:27 +00:00
processed_count += future.result()
pbar.update(len(futures[future]))
2024-12-13 16:43:45 +00:00
return processed_count