LoginSignup
15
14

More than 3 years have passed since last update.

PythonとAPIでディレクトリ内の最新の人物画像の背景除去を自動化する

Last updated at Posted at 2020-03-17

やりたいこと

  1. 人物画像の背景除去
  2. 背景除去する画像のインプット先と背景除去した画像のアウトプット先を細かく指定
  3. フォルダ内の最新の画像の参照
  4. それらの自動化

OpenCVやらfacenetやらを使って画像から顔認識を行い、なんらかの処理を行いたいことがたまにはあるでしょう。もちろんそれらのツールで顔を認識してくれますが、画像内の背景などの不要なものによって “顔認識の精度が劇的に落ちるときがある” ことがわかりました。では、予め背景を取り除いておいてあげて、顔認識の精度を安定させよう!ということで背景除去を行います。まぁ動機はなんでもいいです。

remove.bg

背景除去そのものはremove.bgというWebアプリケーションを使います。どんなもんかは見た方が早いです。
before
Lenna.jpg
after
Lenna-removebg-preview.png
remove.bgはこんな精度の高い背景除去がWeb上で簡単に行えます。

背景除去の自動化

自分が実装中のシステムの一部として、画像が格納されているディレクトリ内の “最新の” 画像を参照して、背景除去を行い、別のディレクトリに結果を返すという構造を自動化していきます。

remove.bgはAPIを公開しているので、それを使って背景除去は自動化できます。会員登録し、通常のアカウントで1ヶ月50回まで無料でAPIを呼び出せます。

# 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_YOUR_API_KEY_HERE'の部分にremove.bgで取得したAPI Keyを挿入します。
画像のインプットとアウトプットの自動化はパス指定で簡単にできます。
'/path/to/file.jpg'の部分に背景除去を行いたい画像のパスを指定します。
'no-bg.png'の部分でアウトプットしたい画像のファイル名を決めてディレクトリのパスを指定できます。

最新画像の参照

今回はmac標準のPhoto Boothというカメラアプリで撮影した“最新の” 画像をインプットしたいので、パス指定は少しだけ工夫します。

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

i_pathで取得したい画像が格納されているディレクトリを指定しています。
glob関数でディレクトリ内の画像一覧を取得しています。
max関数とオプション指定でファイルの日時の最大値、つまり最新の画像が取得できます。

全体のコード

import glob
import os
import requests

i_path = '/Users/username/Pictures/Photo Boothライブラリ/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)

まとめ

remove.bg APIのおかげで背景除去の自動化が非常に簡単に実装できました。
また、最新の画像ファイルの指定という小技もすぐ実装でき、目的を達成しました。
手動で面倒くさい作業はプログラムに投げると楽でいいですね。

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14