Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • PDF Invoice Generator
Menu

Python 3 Rembg Library Script to Bulk Process Multiple Images and Remove Background in Command Line

Posted on May 18, 2023

 

 

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

 

 

Python
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.

 

Recent Posts

  • Node.js Express Project to Remove Background of Images Using Rembg & Formidable Library in Browser
  • Node.js Tutorial to Remove Background From Image Using Rembg & Sharp Library in Command Line
  • Python 3 Flask Project to Remove Background of Multiple Images Using Rembg Library in Browser
  • Python 3 Rembg Library Script to Bulk Process Multiple Images and Remove Background in Command Line
  • Python 3 Rembg Library Script to Remove Background From Image in Command Line
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme