Remove Background from Photos for Holiday Card Creation with Python
You can use open-source tools to produce holiday cards this year. Suppose you have a great photo of your family or grandchildren, but it was taken in a different season, and now you would like to use that photo with a different background. There is a Python module remgb that will do just that. First, you must set up a Python virtual environment and install the necessary extras to accomplish the task. I created a directory called rembg. I do that with the following command:
$ mkdir rembg
Then I setup a Python virtual environment.
python3 -m venv /home/don/rembg
Next I activate the environment with the following command.
source /home/don/rembg/bin/activate
Then I install rembg:
pip3 install rembg
I want to use rembg from the command line so I make the following additional installation:
pip3 install "rembg[cli]"
Then I install onnxruntime which is a machine learning accelerator.
pip3 install onnxruntime
Now I am ready to remove the background from the image that I have chosen. This is a recent picture of my wife and I taken in the fall of the year. I like the picture but I want it to have a festive background.
I ensure my image is in the rembg folder and then execute the following command. The i switch means that I am operating at the file level.
rembg i grandparents.jpg grandparents_no_bg.jpg
In the command above, I renamed the output file to have my original still, just in case I wanted to use it again. You can see below that the background has been removed from the image above.
I can create a nice background for my card with InkScape, add some festive lettering, and use a Pointsettia I downloaded from Openclipart.org. The completed card is shown below.
Rembg is open source and has an MIT License. Onnxruntime is open source and has an MIT License.