LoginSignup
1
1

More than 5 years have passed since last update.

Python+OpenCVで顔検出器の性能比較

Posted at

Python+OpenCVで顔検出器の性能比較

どれが一番目的に合っているのか調べるため比べやすいように出力してみた

コード

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

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

import cv2, os, sys, imghdr

CLASSIFIER_DIR = '/usr/local/share/OpenCV/haarcascades'
CLASSIFIER_LIST = [
    'haarcascade_eye_tree_eyeglasses',
    'haarcascade_eye',
    'haarcascade_frontalface_alt_tree',
    'haarcascade_frontalface_alt',
    'haarcascade_frontalface_alt2',
    'haarcascade_frontalface_default',
    'haarcascade_lefteye_2splits',
    'haarcascade_profileface',
    'haarcascade_righteye_2splits',
    'haarcascade_smile'
]
CLASSIFIERS = {}
for name in CLASSIFIER_LIST:
    CLASSIFIERS[name] = cv2.CascadeClassifier('{classifier_dir}/{classifier}.xml'.format(
        classifier_dir = CLASSIFIER_DIR,
        classifier = name
    ))
CWD = os.getcwd()
DIR_ORIGIN = CWD + '/images/'
DIR_DESTINATION = CWD + '/faces/'

def getFaces(path_full):
    results = {}
    original_image = cv2.imread(path_full)
    gray = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
    for label, classifier in CLASSIFIERS.items():
        image = original_image.copy()
        faces = classifier.detectMultiScale(gray)
        for i in range(len(faces)):
            x, y , w, h = faces[i]
            image = cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 255), 2)
        results[label] = image
    return results

count = 1
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']:
            faces = getFaces(path_full)
            for classifier, face in faces.items():
                file_name = '{destination_dir}/{count}_OpenCV_{classifier}.jpg'.format(
                    destination_dir = DIR_DESTINATION,
                    count = count,
                    classifier = classifier
                )
                cv2.imwrite(file_name, face, [cv2.IMWRITE_JPEG_QUALITY, 100])
            print(path_full)
            count += 1

参考サイト

OpenCV 使用可能なCascadeClassifierの種類と効果

python+OpenCVで顔認識をやってみる

A face-detection script in Python

1
1
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
1
1