Samir Paruthi
Samir Paruthi

Reputation: 121

Tilted head Detection is failed in image but success in live stream

I am working on a project where I need to detect face from the image and store it to directory for further use. I am using openCV (Haar_cascade_classifier) It is detecting only straight head. for detection of the tilted head.I tried tune version haar_cascade.but the problem it is only detecting face in live video.If I run webcamera and detect using haar_cascade_classifier_atl2.xml file . it detect the tilted head but if If I run loop from my image directory and pass images to detect face it is not detecting the same angle.means It is detecting in video but not from image (same angle) here is the code

import cv2
from math import sin, cos, radians
import time
import fnmatch
import os

total_number_of_frame = 0
framedirectory = "D:/finalpaper/extractedframes"
number_of_extracted_frames = len(fnmatch.filter(os.listdir('D:/finalpaper/extractedframes'), '*.png'))
print(number_of_extracted_frames)
face = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_alt2.xml")

settings = {
    'scaleFactor': 1.3,
    'minNeighbors': 3,
    'minSize': (50, 50)
}

def rotate_image(image, angle):
    if angle == 0: return image
    height, width = image.shape[:2]
    rot_mat = cv2.getRotationMatrix2D((width/2, height/2), angle, 0.9)
    result = cv2.warpAffine(image, rot_mat, (width, height), flags=cv2.INTER_LINEAR)
    return result

def rotate_point(pos, img, angle):
    if angle == 0: return pos
    x = pos[0] - img.shape[1]*0.4
    y = pos[1] - img.shape[0]*0.4
    newx = x*cos(radians(angle)) + y*sin(radians(angle)) + img.shape[1]*0.4
    newy = -x*sin(radians(angle)) + y*cos(radians(angle)) + img.shape[0]*0.4
    return int(newx), int(newy), pos[2], pos[3]

for i in range(number_of_extracted_frames):
    framenumber = str(i)+".png"
    #joining path to directory
    filepath = os.path.join(framedirectory,framenumber)
    frame = cv2.imread(filepath)
    for angle in [0, -25, 25]:
        rimg = rotate_image(frame, angle)
        detected = face.detectMultiScale(rimg, **settings)
        if len(detected):
            detected = [rotate_point(detected[-1], frame, -angle)]
        break

     # Make a copy as we don't want to draw on the original image:
    for x, y, w, h in detected[-1:]:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (255,0,0), 2)


    cv2.imshow("frame",frame)
    cv2.waitKey(700)

If above code I use to run with web camera it detect face but if I am using my loop it is not detecting tilted head.

Upvotes: 0

Views: 64

Answers (0)

Related Questions