OpenCV を使って、顔検出してみる
Python
Published: 2019-09-23

やったこと

OpenCV を使って、顔検出してみます。

確認環境

$ python
Python 3.6.2 |Anaconda custom (64-bit)| (default, Sep 21 2017, 18:29:43)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'3.4.2'

調査

すでに学習済みの分類器を使います。 haarcascade_frontalface_alt.xml

import cv2
import sys
import os
import shutil

cascade_path = "./haarcascade_frontalface_alt.xml"

image_path=('/Users/himejima/Desktop/working/satomi-2/1451685134.jpg')
image = cv2.imread(image_path)
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cascade = cv2.CascadeClassifier(cascade_path)
facerect = cascade.detectMultiScale(image_gray, scaleFactor=1.2, minNeighbors=2, minSize=(10, 10))
## print("face rectangle")
## print(facerect)

if len(facerect) > 0:
  path = os.path.splitext(image_path)

for rect in facerect:
  # 顔だけ切り出して保存
  x = rect[0]
  y = rect[1]
  width = rect[2]
  height = rect[3]
  dst = image[y:y+height, x:x+width]
  new_image_path = './' + str(0) + path[1];
  # print(new_image_path)
  cv2.imwrite(new_image_path, dst)

参考