Remove background from single image
Discover how to remove the background from an image using the rembg package's function remove and then save the edited image wherever you want on your computer thanks to the os library.
MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.
There are two more packages to import because we want to show you the effect of removing the background.
# import packages
from IPython.display import display, HTML
from PIL import Image
import os
from rembg import remove
We used Show Image piece of code here. Get more information here: How to show image in Jupyter Notebook.
# variables:
path="/home/apjanusz/images/goryl.png"
size=500,500
# code:
with Image.open(path) as i:
i.thumbnail(size)
display(i)
This simple piece of code allows you to remove the background from any image and save it in any directory:
# variables:
input_image = "/home/apjanusz/images/goryl.png"
output_image = os.path.join(r"", "gorylOutput.png")
# code:
with open(input_image, "rb") as i:
with open(output_image, "wb") as o:
input = i.read()
output = remove(input)
o.write(output)
Let us show you the final effect:
# variables:
path="/home/apjanusz/gorylOutput.png"
size=500,500
# code:
with Image.open(path) as i:
i.thumbnail(size)
display(i)
Below there is a video, which shows how this notebook was created. Enjoy!
HTML("""<iframe width="530" height="315" src="https://www.youtube.com/embed/QJLlN2MaCrM?si=c_ucrt7y1OLQMNdA" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>""")
Conclusions
As you can see, removing the background from image isn't that hard. All you need is a little willingness and a good teacher such as MLJAR Studio.
We will be happy to teach you :)
Recipes used in the remove-single-image-background.ipynb
All code recipes used in this notebook are listed below. You can click them to check their documentation.
Packages used in the remove-single-image-background.ipynb
List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.
rembg>=2.0.57
Similar notebooks
List of similar Python notebooks, so you can find more inspiration ๐