OpenCVを顔検出して、顔の部分だけ切り取ることを行います。
モジュールをimport
import cv2 from os import path import numpy as np from matplotlib import pyplot as plt %matplotlib inline
CascadeClassifierを選定
cascades_dir = path.normpath(path.join(cv2.__file__, '..', '..', '..', '..', 'share', 'OpenCV', 'haarcascades')) cascade_f = cv2.CascadeClassifier(path.join(cascades_dir, 'haarcascade_frontalface_alt2.xml'))
顔を検出するためにhaarcascade_frontalface_alt2を読み込みます。他のCascadeClassifierは下記を参考。
顔を検出するコード
def faceDetect(filePath): img = cv2.imread(filePath) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = cascade_f.detectMultiScale(img, 1.3, 5) if len(faces) > 0: cnt = 1 for(x, y, w, h) in faces: # 顔を四角で囲む cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # 顔だけを表示 cut_face_img = img[y:y+h,x:x+w] # 横一列に顔を表示 plt.subplot(1, len(faces), cnt) plt.imshow(cv2.cvtColor(cut_face_img, cv2.COLOR_BGR2RGB)) cnt += 1 plt.show() else: print 'no face' plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show() faceDetect('images/test.jpg')
結果
https://twitter.com/naoyashiga/status/822595990381326339
https://twitter.com/naoyashiga/status/822596186343346176
複数の顔も認識。正面の顔じゃないとキツイみたいだ。
画像を横並べに表示
matplotlibのsubplotを使うようです。