Automate background removal for the latest portraits in a directory with Python and API

Thing you want to do

  1. Removal of background of portrait image
  2. Specify the input destination of the image to be removed background and the output destination of the image to be removed background in detail.
  3. Browse the latest images in the folder
  4. Those automation

Occasionally you may want to use OpenCV or facenet to perform face recognition from an image and do some processing. Of course, those tools will recognize the face, but I found that unnecessary things such as the background in the image "may dramatically reduce the accuracy of face recognition". Now, let's remove the background in advance to stabilize the accuracy of face recognition! So we will remove the background. Well, any motive is fine.

remove.bg The background removal itself uses a web application called remove.bg. It's faster to see what it's like. before Lenna.jpg after Lenna-removebg-preview.png remove.bg makes it easy to remove backgrounds with such high accuracy on the Web.

Automation of background removal

As part of the system I'm implementing, I'll automate the structure of looking at the "latest" images in the directory where the images are stored, removing the background, and returning the results to another directory. ..

remove.bg exposes an API that you can use to automate background removal. You can register as a member and call the API for free up to 50 times a month with a regular account.

# Requires "requests" to be installed (see python-requests.org)
import requests

response = requests.post(
    'https://api.remove.bg/v1.0/removebg',
    files={'image_file': open('/path/to/file.jpg', 'rb')},
    data={'size': 'auto'},
    headers={'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE'},
)
if response.status_code == requests.codes.ok:
    with open('no-bg.png', 'wb') as out:
        out.write(response.content)
else:
    print("Error:", response.status_code, response.text)

Insert the API Key obtained by remove.bg in the part of'INSERT_YOUR_API_KEY_HERE'. You can easily automate the input and output of images by specifying the path. Specify the path of the image you want to remove the background in the part of'/path/to/file.jpg'. You can specify the directory path by deciding the file name of the image you want to output in the'no-bg.png'part.

Refer to the latest image

This time, I want to input the "latest" image taken with the standard mac camera application called Photo Booth, so I will devise a little path specification.

i_path = '/Users/username/Pictures/Photo Booth library/Pictures/*'
list_of_files = glob.glob(i_path) 
latest_file = max(list_of_files, key=os.path.getctime)

The directory where the image you want to get with i_path is stored is specified. I am getting a list of images in the directory with the glob function. You can get the maximum value of the date and time of the file, that is, the latest image by specifying the max function and options.

Whole code

import glob
import os
import requests

i_path = '/Users/username/Pictures/Photo Booth library/Pictures/*'
list_of_files = glob.glob(i_path) 
latest_file = max(list_of_files, key=os.path.getctime)

# RemoveBgAPI
response = requests.post(
    'https://api.remove.bg/v1.0/removebg',
    files={'image_file': open(latest_file, 'rb')},
    data={'size': 'auto'},
    headers={'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE'},
)
if response.status_code == requests.codes.ok:
    with open('/Users/username/output/no-bg.png', 'wb') as out:
        out.write(response.content)
    print('Success!')
else:
    print("Error:", response.status_code, response.text)

Summary

The remove.bg API made it very easy to implement background removal automation. In addition, I was able to quickly implement the trick of specifying the latest image file, and achieved my goal. It's nice to throw the troublesome work manually into the program.

Recommended Posts

Automate background removal for the latest portraits in a directory with Python and API
Parse the Researchmap API in Python and automatically create a Word file for the achievement list
Replace the directory name and the file name in the directory together with a Linux command.
[Python] Get the files in a folder with Python
Created a Python wrapper for the Qiita API
Tips for hitting the ATND API in Python
Archive and compress the entire directory with python
[Python] Created a class to play sin waves in the background with pyaudio
Turn multiple lists with a for statement at the same time in Python
How to get a list of files in the same directory with python
Create a clean DB for testing with FastAPI and unittest the API with pytest
Playing with a user-local artificial intelligence API in Python
Build a python environment for each directory with pyenv-virtualenv
Fill the background with a single color with OpenCV2 + Python
Install the latest stable Python with pyenv (both 2 and 3)
Build API server for checking the operation of front implementation with python3 and Flask
[Python] Change the text color and background color of a specific keyword in print output
Call the API with python3.
Create a directory with python
Try hitting the Twitter API quickly and easily with Python
A note about hitting the Facebook API with the Python SDK
Create a child account for connect with Stripe in Python
Installation procedure for Python and Ansible with a specific version
[Note] Import of a file in the parent directory in Python
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Library for specifying a name server and dig with python
Shuffle the images in any directory with Python and save them in another folder with serial numbers.
Recursively get the Excel list in a specific folder with python and write it to Excel.
I also tried to imitate the function monad and State monad with a generator in Python
Getting the arXiv API in Python
Hit the Sesami API in Python
Create a striped illusion with gamma correction for Python3 and openCV3
Create a color picker for the color wheel with Python + Qt (PySide)
The story of making a standard driver for db with python.
[Introduction to Python] How to use the in operator in a for statement?
Hit the Etherpad-lite API with Python
Draw a watercolor illusion with edge detection in Python3 and openCV3
Understand the probabilities and statistics that can be used for progress management with a python program
Hit the web API in Python
Read a file in Python with a relative path from the program
[Python3] Save the mean and covariance matrix in json with pandas
Dockerfile with the necessary libraries for natural language processing in python
Solve the Python knapsack problem with a branch and bound method
Create a CGH for branching a laser in Python (laser and SLM required)
Firebase Authentication token issuance in Python and token verification with Fast API
Access the Twitter API in Python
Solve the subset sum problem with a full search in Python
How to send a request to the DMM (FANZA) API with python
Command for the current directory Python
When I cut the directory for UNIX Socket under / var / run with systemd, I got stuck in a pitfall and what to do
Fill the string with zeros in python and count some characters from the string
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
A memo organized by renaming the file names in the folder with python
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
How to get the date and time difference in seconds with python
python> array> Determine the number and initialize> mylist = [idx for idx in range (10)] / mylist = [0 for idx in range (10)] >> mylist = [0] * 10
Read a Python # .txt file for a super beginner in Python with a working .py
I set the environment variable with Docker and displayed it in Python
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Hit a method of a class instance with the Python Bottle Web API
Get and convert the current time in the system local timezone with python