Open In App

How to remove the Background from an image using Python?

Last Updated : 30 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll learn how to remove the background of an image using Python.

Pillow module:

The Pillow library, a derivative of the Python Imaging Library (PIL), aids in giving Python interpreter image processing capabilities. This library offers a wide range of file format support, a productive internal representation, and moderately potent image-processing skills. The core image library was created to provide quick access to data contained in a few fundamental pixel formats. It ought to offer a reliable framework for a broad image processing tool. Execute the following command in the Terminal Window to install it:

pip install Pillow

Rembg module:

The rembg module is used to remove the background of the given image. Execute the following command in the Terminal Window to install it:

pip install rembg

Steps to remove the image background using Python

Step 1: Import required modules.

Step 2: Read the image using the path of the image.

Step 3: Open the image using the Image.open() function.

Step 4: Remove the background of the image using the remove() function.

Step 5: Save the output image using output.save() function.

Remove the background of an image using Python

To remove the background of an image using Python firstly we have to import the required modules which we have installed using the pip command. Defining two variables “input_path” and “output_path” where input_path stores the path of image of which background to be removed and output_path stores the path where a new image with removed background has to be saved. Now open the image using Image.open() function and then remove the background of the image using the remove() function. In the last step save the processed image at the location stored in output_path using output.save() function.

Python3




# Importing Required Modules
from rembg import remove
from PIL import Image
  
# Store path of the image in the variable input_path
input_path =  'E:\C programs\
               Remove BackGround\gfgimage.png'
  
# Store path of the output image in the variable output_path
output_path = 'E:\C programs\
               Remove BackGround\gfgoutput.png'
  
# Processing the image
input = Image.open(input_path)
  
# Removing the background from the given Image
output = remove(input)
  
#Saving the image in the given path
output.save(output_path)


Input Image:

Input Image: Before removing the Background

Output Image:

Output Image: After removing the Background


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads