Removing background using python
@Thakur666
June 01, 2026
Setting up environment
Create a virtual environment
- Create a project directory
removebackgroundand change into that project directory
mkdir removebackground
cd removebackground
- Creating a
venv_removebackgroundvirtual environment.
python -m venv venv_removebackground
- Activate that virtual environment
.\venv_removebackground\Scripts\activate
-install pip
pip install rembg pillow
Code Lets say the code name removebackground.py
from rembg import remove
from PIL import Image
import os
def remove_background(input_image_path, output_image_path):
try:
input_image = Image.open(input_image_path)
output_image = remove(input_image)
output_image.save(output_image_path)
print(f"background remove succesfully")
print(f"saved as: {output_image_path}")
except Exception as e:
print(f"error: {e}")
if __name__ =="__main__":
input_path = input("enter input image path :").strip()
filename, _ =os.path.splitext(input_path)
output_path = f"{filename}_no_bg.png"
remove_background(input_path, output_path)
NOTE
Make sure you copy the file into the same path, where you are running this code. Or give the absolute path of the file.
Before Demo Image
Execute your code
python.exe removebackground.py

