41
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

OpenCVでアニメの顔検出

Posted at

下準備

import cv2できるようにする
・特徴量ファイルを読み込めるようにする

こちら参照
Mac OS X で OpenCV 3 + Python 2/3 の開発環境を整備する方法

分類器の作成と顔の位置検出

import os
import cv2

# 特徴量ファイルをもとに分類器を作成
classifier = cv2.CascadeClassifier('lbpcascade_animeface.xml')

# 顔の検出
image = cv2.imread('newGame.jpg')
# グレースケールで処理を高速化
gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
faces = classifier.detectMultiScale(gray_image)

print(faces)で6人分の顔の位置と大きさが検出できたのを確認

[[485 148 134 134]
 [456 313 193 193]
 [380  58  98  98]
 [649 227 127 127]
 [373 245 108 108]
 [637  54 104 104]]

一人ずつ顔を切り抜く

# ディレクトリを作成
output_dir = 'faces'
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
    
for i, (x,y,w,h) in enumerate(faces):
    # 一人ずつ顔を切り抜く
    face_image = image[y:y+h, x:x+w]
    output_path = os.path.join(output_dir,'{0}.jpg'.format(i))
    cv2.imwrite(output_path,face_image)
    
cv2.imwrite('face.jpg',image)

スクリーンショット 2017-08-13 3.33.43.png

顔を四角で囲う

for x,y,w,h in faces:
    # 四角を描く
    cv2.rectangle(image, (x,y), (x+w,y+h), color=(0,0,255), thickness=3)
    
cv2.imwrite('faces.jpg',image)

faces.jpg

特徴量ファイル一覧

haarcascade_eye.xml
haarcascade_eye_tree_eyeglasses.xml
haarcascade_frontalcatface.xml
haarcascade_frontalcatface_extended.xml
haarcascade_frontalface_alt.xml
haarcascade_frontalface_alt2.xml
haarcascade_frontalface_alt_tree.xml
haarcascade_frontalface_default.xml
haarcascade_fullbody.xml
haarcascade_lefteye_2splits.xml
haarcascade_licence_plate_rus_16stages.xml
haarcascade_lowerbody.xml
haarcascade_profileface.xml
haarcascade_righteye_2splits.xml
haarcascade_russian_plate_number.xml
haarcascade_smile.xml
haarcascade_upperbody.xml

今回使用したlbpcascade_animeface.xmlはこちら
https://github.com/nagadomi/lbpcascade_animeface

参考
http://gihyo.jp/book/2017/978-4-7741-8367-1

41
39
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
41
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?