Monday, September 4, 2023

Remove background from picture using command line

Removing a picture's background is sometimes a necessity, especially if you need the picture to integrate into other document or other picture. Here I will show how we can achieve that in linux using a python application called rembg.


First, make sure we have python installed. Most linux will have it installed by default, but just check to make sure
$ python -V






In order avoid installing python libraries globally, we will create a virtual environment to keep the rembg application files. You can read more about virtual environment, by clicking here. So we will create a virtual environment called rembg
$ python3 -m venv rembg

Activate the virtual environment
$ cd rembg
$ source bin/activate

Update pip
(rembg) $ pip install --upgrade pip

Install rembg[cli] package
(rembg) $ pip install rembg[cli]

Once installed, we can use "--help" to see what are the options available for rembg
$ rembg --help

Now we can use rembg to remove background. Let's say we have a picture called mypicture.jpg, and we want to remove its background, and save the new picture as mypicture-nobg.jpg:
(rembg) $ rembg i mypicture.jpg mypicture-nobg.jpg

Verify that the background has been removed in the new picture.

rembg also comes with http-server, for those who wanted a web interface to remove background from picture. Just run rembg with "s" flag to launch the rembg http server
$ rembg s

A web app will be launched on http://localhost:5000, where you can upload the file to be background removed, and click submit to get the output.

























Simply press "ctrl + c" to cancel rembg's http server, when you are done.

No comments: