Remove Image Background in Python with rembg — AI Background Removal Example
A short Python script that shows how to remove the background from an image in Python using the AI-based rembg library, then places the subject on a solid black background with Pillow.
Overview
This script takes an input image, removes its background using the AI-powered rembg library, and composites the foreground onto a solid black canvas. The result is saved as a new image file.
Features
- Automatic background removal using
rembg(powered by U²-Net deep learning model) - Composites the transparent result onto a solid black background
- Accepts any image format supported by Pillow as input
- Output saved as a separate file (original is preserved)
Requirements
rembg
Pillow
Install dependencies:
pip install rembg Pillow
On first run,
rembgwill download the U²-Net model (~170 MB). This only happens once.
Usage
By default the script processes the included sample image Elephant.jpg and writes Elephant_Modified.jpg, so you can try it straight away from the Console_Code folder:
python Remove.py
To use your own image, set the input and output paths in Remove.py:
orginal_image = 'path/to/input.jpg'
output_image = 'path/to/output.jpg'
The processed image will be saved at the output path.
How It Works
- The input image is opened and converted to PNG bytes (required by
rembg). rembg.remove()applies the background removal model.- The resulting RGBA image (with transparent background) is pasted onto a new black RGB canvas.
- The final image is saved to the output path.
File Structure
Remove Background/
└── Console_Code/
├── Remove.py # Main script
└── Elephant.jpg # Sample input image
Notes
- The output background color is currently set to black. Change
'black'to'white'or any other color inImage.new('RGB', result_img.size, 'black')to use a different background. rembgworks best on images with clear subject-background contrast.- To keep a transparent background instead, save
result_img(the RGBA image) as a.pngfile rather than compositing it onto a colour. - The function’s docstring and variable name mention a white background, but the code uses
'black'.
Related Projects
- Image2Cartoon — cartoon effect with OpenCV
- Photo to graphite pencil sketch CLI
- Back to all Python projects
Documentation links
Read all Python Projects and Code Examples guides online · Project overview · All developer projects