Remove background of an image with only 5 lines of code

Posted by Afsal on 02-Dec-2022

Hi Pythonistas

Today we are learning how to remove an image's background with only 5 lines of code. For that, we need a package called rembg. Let us dive into the code

Prerequisite

Python >3.7, <3.11

Installation

pip install rembg

Code

from rembg import remove
from PIL import Image

#load image input image
#here I load a sample image dada.png
input_image = Image.open("dada.png")

#call the remove function with the input image
output = remove(input_image)

#Save the background removed image to
#File dada_new.png
output.save("dada_new.png")

dada.png

dada_new.png

I hope you have learned something from this post. Share your valuable suggestions with afsal@parseltongue.co.in