0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

anime-face-detector で顔検出

0
Posted at

前の記事

導入

前回の方法ではリアル三次元系の顔はきちんと検出できるのかも知れませんが、ぶっちゃけ三次元には興味ないのと、検出精度が良くなかったので、二次元に特化した YOLOv3 へ移行します。

二 次 元 し か 勝 た ん

用意するもの

CUDA が使える NVIDIA 製グラフィックスカード。

環境作り

新しく適当なワークフォルダを用意します。

DOS> python -m venv venv
DOS> venv\Scripts\activate

まず pip を最新版へアップグレード。

(venv) DOS> python -m pip install --upgrade pip

次は torch のインストール。うちの環境では CUDA 12.1 を使います。

(venv) DOS> pip install torch==2.5.1 torchvision==0.20.1 --index-url https://download.pytorch.org/whl/cu121

動作チェック

(venv) DOS> python -c "import torch; import numpy as np; print('torch:', torch.__version__); print('CUDA:', torch.version.cuda); print('CUDA available:', torch.cuda.is_available()); print('NumPy:', np.__version__); print(torch.from_numpy(np.array([1,2,3])))"
torch: 2.5.1+cu121
CUDA: 12.1
CUDA available: True
NumPy: 2.5.2
tensor([1, 2, 3])

anime-face-detector をインストール。

(venv) DOS> pip install anime-face-detector

準備はできました。

まず顔検出してみる

input と output フォルダは別途作っておいてください。手抜きなのでプログラムでは作りません。input フォルダには「sample_番号.png」のような名前でサンプル画像を置いてください。

import cv2
import glob
import os
from anime_face_detector import create_detector

detector = create_detector("yolov3", device="cuda:0")

for fn in glob.glob(f"output/*.png"):
        os.remove(fn)

for filename in glob.glob("input/*.png"):
    b_name = os.path.basename(filename)
    o_name = os.path.splitext(b_name)[0]
    img = cv2.imread(filename)

    preds = detector(img)
    if preds is None:
        print(f"{b_name}: 顔を検出できませんでした")
        continue
    print(f"{b_name} 検出数: {len(preds)}")

    for i, pred in enumerate(preds):
        x1, y1, x2, y2, score = pred["bbox"]

        cv2.rectangle(
            img,
            (int(x1), int(y1)),
            (int(x2), int(y2)),
            (0, 255, 0),
            3
        )

        cv2.putText(
            img,
            f"{score:.3f}",
            (int(x1), int(y1) - 10),
            cv2.FONT_HERSHEY_SIMPLEX,
            1,
            (0, 255, 0),
            2
        )

    out_filename = f"output/{o_name}_face_detect.png"
    cv2.imwrite(out_filename, img)
    print(f"保存しました: {out_filename}")

実行すると以下の警告がでますが無視で構いません。

Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.

結果

10 ファイル分処理してみましたが、すべて正常に顔を検出しました。スコアは高く誤検出もなく素晴らしい結果です。

次回

次回はランドマークの表示をやる予定です。つづく。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?