LoginSignup
2
3

More than 5 years have passed since last update.

Python+OpenCVで顔検出

Posted at

Python+OpenCVで顔検出

インストール

少し面倒なので、以下あたりを参考に

Install OpenCV 3.0 and Python 2.7+ on Ubuntu

Install OpenCV 3.0 and Python 2.7+ on OSX

MacでOpenCVとpythonを使う

Python 環境のインストール

コード

分類器のある場所は環境に合わせて変更
which python
とか
which python3
でpythonの場所を調べたら、インストールされていればその周辺にあるのではないかと

detect_face.py
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import cv2, os, sys, imghdr, shutil

CLASSIFIERS = (
    'haarcascade_frontalcatface_extended.xml',
    'haarcascade_frontalcatface.xml',
    'haarcascade_frontalface_alt_tree.xml',
    'haarcascade_frontalface_alt.xml',
    'haarcascade_frontalface_alt2.xml',
    'haarcascade_frontalface_default.xml',
)
PATH_CLASSIFIER = '{python_dir}/{classifier_dir}/{classifier}'.format(
    python_dir = os.path.split(sys.executable)[0],
    classifier_dir = '../share/OpenCV/haarcascades',
    classifier = CLASSIFIERS[4]
)
CWD = os.getcwd()
DIR_ORIGIN = CWD + '/images/'
DIR_DONE = CWD + '/done/'
DIR_NONE = CWD + '/none/'
DIR_DESTINATION = CWD + '/faces/'

classifier = cv2.CascadeClassifier(PATH_CLASSIFIER)

def mkdir(path):
    dirs = path.split('/')
    current = ''
    for d in dirs:
        current += d + '/'
        if not os.path.exists(current):
            os.mkdir(current)

def moveFile(origin_path, dest_dir):
    mkdir(dest_dir)
    shutil.move(origin_path, dest_dir)

def getFaces(path_full):
    image = cv2.imread(path_full)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    faces = classifier.detectMultiScale(gray)
    path, name = os.path.split(path_full)
    path_destination = path.replace(DIR_ORIGIN, DIR_DESTINATION)
    dir_done = path.replace(DIR_ORIGIN, DIR_DONE)
    dir_none = path.replace(DIR_ORIGIN, DIR_NONE)
    base_name = os.path.join(path_destination, name[:name.rfind('.')])
    count = len(faces)
    for i in range(count):
        x, y , w, h = faces[i]
        crop = image[y : y + h, x : x + w]
        file_name = base_name
        file_name += ('_' + str(i + 1)) if count > 1 else ''
        file_name += '.jpg'
        mkdir(path_destination)
        cv2.imwrite(file_name, crop, [cv2.IMWRITE_JPEG_QUALITY, 100])
    if count:
        moveFile(path_full, dir_done)
    else:
        moveFile(path_full, dir_none)
    return count

def isEmpty(dir_):
    return True if not os.listdir(dir_) else False

count = 0
for path, subdirs, files in os.walk(DIR_ORIGIN):
    for name in files:
        path_full = os.path.join(path, name)
        if imghdr.what(path_full) in ['jpeg']:
            count = getFaces(path_full)
    if count:
        if isEmpty(path):
            os.rmdir(path)
        count = 0
2
3
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
2
3