To bulk remove the background of all images stored in an input directory using the rembg
library in Python 3 and save the output images in an output directory, you can use the following script:
pip install rembg
And after that you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import os from rembg import remove def remove_background(input_dir, output_dir): # Create the output directory if it doesn't exist os.makedirs(output_dir, exist_ok=True) # Get the list of image files in the input directory image_files = [f for f in os.listdir(input_dir) if f.endswith(('.png', '.jpg', '.jpeg'))] for image_file in image_files: input_path = os.path.join(input_dir, image_file) output_path = os.path.join(output_dir, image_file) with open(input_path, 'rb') as f_in: with open(output_path, 'wb') as f_out: img_data = f_in.read() output_data = remove(img_data) f_out.write(output_data) print(f"Background removed: {output_path}") # Specify the input and output directories input_directory = 'path/to/input/directory' output_directory = 'path/to/output/directory' # Call the function to remove the background of images in bulk remove_background(input_directory, output_directory) |
Make sure to replace 'path/to/input/directory'
with the actual path to your input directory containing the images, and 'path/to/output/directory'
with the desired path where you want to save the output images.
The script uses the rembg
library to remove the background of each image file. It iterates over the image files in the input directory, reads each image, applies the background removal, and saves the output image in the output directory with the same file name.