Python : How to remove background of an image using Python

python @ Freshers.in

In this article we will see how can we remove background of an image using Python. For this we are using “rembg” . rembg is a tool to remove images background. Another library that we use is Pillow. Once you have pip installed these we can start working on this. Its is preferable to install this on Python 3.8+ . Here I used Python 3.10. There may be some dependency while working on this . We have described the steps that you can take care if you face some error. 

Python Background remove @ Freshers.in

Libraries to install : 

pip install rembg
pip install Pillow

Sample Code 

from rembg import remove
from PIL import Image
raw_file_name = "tiger.jpg"
processed_image_file= "tiger_only.png"

Read=>Process Image => Write to File

in_file = Image.open(raw_file_name)
remove_background = remove(in_file)
remove_background.save(processed_image_file)

To compare old and new updated image

Raw Image

from IPython.display import Image 
raw_img = Image(filename=raw_file_name)
display(raw_img)

Processed Image 

final_img = Image(filename=processed_image_file)
display(final_img)

What are the issues that you may have during execution

Access denied with the following error:

 	Too many users have viewed or downloaded this file recently. Please
	try accessing the file again later. If the file you are trying to
	access is particularly large or is shared with many people, it may
	take up to 24 hours to be able to view or download the file. If you
	still can't access a file after 24 hours, contact your domain
	administrator. 

You may still be able to access the file from the browser:

	 https://drive.google.com/uc?id=1tCU5MM1LhRgGou5OpmpjBQbSrYIUoYab

If you face the above means that you may need to add some models files in your instance or computer. Normally in the error message it self you will get the link to download the file 

All models need to be downloaded and saved in the user home folder in the .u2net directory.

u2net :- A pre-trained model for general use cases.
Download 1  Download 2
u2netp:- A lightweight version of u2net model.
Download 1 Download 2
u2net_human_seg :- A pre-trained model for human segmentation.

Download 1 Download 2
u2net_cloth_seg :- A pre-trained model for Cloths Parsing from human portrait. Here clothes are parsed into 3
category: Upper body, Lower body and Full body.
Download 1 Download 2

The downloaded files are 

u2net.onnx 168 MB
u2net.pth 168 MB
u2netp.onnx 4.4 MB
u2netp.pth 4.5 MB

You need to put the above downloaded files in your home folder as below
Windows :  C:\Users\username\.u2net\
linux :  /home/username
mac :  /Users/username

Get more post on Python, PySpark

Author: user

Leave a Reply