Face detection with Python + OpenCV (rotation invariant)

Face detection with Python + OpenCV (rotation invariant)

Face detection while rotating the image I haven't adjusted the best angle If necessary, refer to the following

Simple face detection API with Heroku + OpenCV

Face Detection using Haar Cascades

I want you to rotate the filter instead of the input image and detect it automatically ...

Fitting point

It may be natural for people who are accustomed to image processing, but since I have hardly done it, I am quite addicted to it.

The order may be different when acquiring and specifying the height and width of the image.

--shape… height (rows), width (columns) --Slice by index ... [Lower height (y): Upper limit height (y + h), Lower limit width (x): Upper limit width (x + w)] --OpenCV coordinate specification (center point, etc.) ... (horizontal (x), vertical (y))

The coordinate system of the display has a downward y-axis, but the angle is counterclockwise, so when the normal y-axis is converted to an upward coordinate system, it rotates clockwise.

code

face_rotate_detect.py


# -*- coding: utf-8 -*-

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

import cv2, os, sys, imghdr, shutil, math
import numpy as np

CWD = os.getcwd()
DIR_ORIGIN = CWD + '/images/'
DIR_DESTINATION = CWD + '/faces/'

classifier = cv2.CascadeClassifier('{python_dir}/{classifier_dir}/haarcascade_frontalface_alt2.xml'.format(
    python_dir = os.path.split(sys.executable)[0],
    classifier_dir = '../share/OpenCV/haarcascades',
))

def getFaces(path_full):
    results = []
    image = cv2.imread(path_full)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    rows, cols, colors = image.shape
    center = tuple(np.array([cols, rows]))
    # get rotations
    for angle in range(-90, 91, 5):
        radian = np.deg2rad(angle)
        output_height = int(np.absolute(cols * np.sin(radian)) + np.absolute(rows * np.cos(radian)))
        output_width = int(np.absolute(cols * np.cos(radian)) + np.absolute(rows * np.sin(radian)))
        output_size = tuple(np.array([output_width, output_height]))
        # rotate
        Matrix = cv2.getRotationMatrix2D(center, degree, 1.0)
        # translate
        Matrix[0, 2] += (output_width - width) * 0.5
        Matrix[1, 2] += (output_height - height) * 0.5
        # warp affine
        rotated = cv2.warpAffine(gray, Matrix, output_size, flags = cv2.INTER_LINEAR)
        # detect faces
        faces = classifier.detectMultiScale(rotated)
        if len(faces):
            rotated_color = cv2.warpAffine(image, Matrix, output_size, flags = cv2.INTER_LINEAR)
            for x, y, w, h in faces:
                results.append(rotated_color[y : y + h, x : x + w])
    return results

def saveFaces(faces):
    global count

    for face in faces:
        cv2.imwrite(
            '{dir_destination}{count}.jpg'.format(dir_destination = DIR_DESTINATION, count = count),
            face,
            [cv2.IMWRITE_JPEG_QUALITY, 100]
        )
        count += 1

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']:
            saveFaces(getFaces(path_full))
            print(path_full)

Recommended Posts

Face detection with Python + OpenCV (rotation invariant)
Face detection with Python + OpenCV
Hello World and face detection with OpenCV 4.3 + Python
Face detection with Python + dlib
Anime face detection with OpenCV
Face detection with YOLO Face (Windows10, Python3.6)
Face detection with Lambda (Python) + Rekognition
[Python] Using OpenCV with Python (Edge Detection)
Make OpenCV object detection rotation invariant
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)
[python, openCV] base64 Face recognition with images
Binarization with OpenCV / Python
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)
Real-time edge detection with OpenCV
[Ubuntu] [Python] Face detection comparison between dlib and OpenCV
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
Improve detection accuracy quickly by specifying parameters with openCV face detection
A memo when face is detected with Python + OpenCV quickly
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
I tried face detection with MTCNN
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
Draw a watercolor illusion with edge detection in Python3 and openCV3
Hello World and face detection with opencv-python 4.2
Save video frame by frame with Python OpenCV
Python dlib face detection and blink counter
Capturing images with Pupil, python and OpenCV
I tried non-photorealistic rendering with Python + opencv
Image processing with Python & OpenCV [Tone Curve]
Image acquisition from camera with Python + OpenCV
Create miscellaneous Photoshop videos with Python + OpenCV ③ Create miscellaneous Photoshop videos
[Python] Read images with OpenCV (for beginners)