前回の記事
環境整備
InsightFace の 106 点ランドマークを使いたいので必要です。
(venv) DOS> python -m pip install insightface
CUDA 版の ONNX Runtime に入れ替えます。
(venv) DOS> python -m pip uninstall onnxruntime -y
(venv) DOS> python -m pip install onnxruntime-gpu
サンプルコード
import cv2
import glob
import os
import numpy as np
from anime_face_detector import create_detector
from insightface.app.common import Face
from insightface.model_zoo.landmark import Landmark
detector = create_detector("yolov3", device="cuda:0")
# ユーザ名 XXXXX の部分は適宜変更してください。
landmark_model = Landmark(
r"C:\Users\XXXXX\.insightface\models\buffalo_l\2d106det.onnx"
)
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):
bx1, by1, bx2, by2, score = pred["bbox"]
x1, y1, x2, y2 = map(int, [bx1, by1, bx2, by2])
margin = 50
x1 = max(0, x1 - margin)
y1 = max(0, y1 - margin)
x2 = min(img.shape[1], x2 + margin)
y2 = min(img.shape[0], y2 + margin)
face_crop = img[y1:y2, x1:x2]
output = cv2.resize(face_crop, None, fx=4, fy=4, interpolation=cv2.INTER_NEAREST)
bbox = np.array([bx1, by1, bx2, by2], dtype=np.float32)
face = Face(bbox=bbox, det_score=float(score))
landmark_model.get(img, face)
landmark = face.landmark_2d_106
for j, point in enumerate(landmark):
x, y = point.astype(int)
x = (x - x1) * 4
y = (y - y1) * 4
cv2.circle(output, (x, y), 2, (0, 0, 255), -1)
cv2.putText(output, str(j), (x + 3, y + 12), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 127, 0), 2, cv2.LINE_AA)
out_filename = f"output/{o_name}_detect_{i}.png"
cv2.imwrite(out_filename, output)
print(f"保存しました: {out_filename}")
結果
顔を検出して、クリップしたのち 4 倍に拡大して、ランドマークを打ちます。