Face detection with Python + OpenCV

Face detection with Python + OpenCV

Installation

It's a little troublesome, so refer to the following

Install OpenCV 3.0 and Python 2.7+ on Ubuntu

Install OpenCV 3.0 and Python 2.7+ on OSX

Using OpenCV and python on Mac

Install Python environment

code

The location of the classifier changes according to the environment which python And which python3 I looked up the location of python and found that if it was installed, it might be around it.

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

Recommended Posts

Face detection with Python + OpenCV
Anime face detection with OpenCV
Hello World and face detection with OpenCV 4.3 + Python
Face detection with YOLO Face (Windows10, Python3.6)
Face detection with Lambda (Python) + Rekognition
[Python] Using OpenCV with Python (Edge Detection)
Try face recognition with python + OpenCV
Cut out face with Python + OpenCV
Face recognition with camera with opencv3 + python2.7
[Python] Face detection by OpenCV (Haar Cascade)
Binarization with OpenCV / Python
[python, openCV] base64 Face recognition with images
Performance comparison of face detector with Python + OpenCV
Resize, mosaic, face detection with OpenCV, sometimes Zojirushi
Face recognition with Python's OpenCV
"Apple processing" with OpenCV3 + Python3
Try edge detection with OpenCV
Image editing with python OpenCV
Camera capture with Python + OpenCV
[Python] Using OpenCV with Python (Basic)
Face detection summary in Python
Face recognition / cutting with OpenCV
Blockchain tampering detection with Python
Try face recognition with Python
Face detection with Haar Cascades
Using OpenCV with Python @Mac
[Ubuntu] [Python] Face detection comparison between dlib and OpenCV
Shining life with Python and OpenCV
[Python] Using OpenCV with Python (Image Filtering)
Neural network with OpenCV 3 and Python 3
[Python] Using OpenCV with Python (Image transformation)
Easy Python + OpenCV programming with Canopy
[OpenCV] Personal identification with face photo
OpenCV feature detection with Google Colaboratory
Load gif images with Python + OpenCV
Cat detection with OpenCV (model distribution)
Find image similarity with Python + OpenCV
Use OpenCV with Python 3 in Window
Draw an illustration with Python + OpenCV
Track baseball balls with Python + OpenCV
Graph Based Segmentation with Python + OpenCV
I tried face recognition with OpenCV
Draw arrows (vectors) with opencv / python
Basic study of OpenCV with Python
Improve detection accuracy quickly by specifying parameters with openCV face detection
A memo when face is detected with Python + OpenCV quickly
Hello World and face detection with opencv-python 4.2
FizzBuzz with Python3
Scraping with Python
Statistics with python
Python2.7 + CentOS7 + OpenCV3
Scraping with Python
Save video frame by frame with Python OpenCV
Python with Go
Python dlib face detection and blink counter
Capturing images with Pupil, python and OpenCV
Twilio with Python
Play with 2016-Python
I tried non-photorealistic rendering with Python + opencv
Tested with Python
Draw a watercolor illusion with edge detection in Python3 and openCV3