Search code examples
pythonopencvhaar-classifier

How to get full head image from haar cascade


i used the following code to capture a face using Haar cascade classifier but still have not get full head image

from imutils.video import WebcamVideoStream
import os
import time
from datetime import datetime
from imutils.video import FPS
import cv2
cascadePath = "/home/pi/opencv-3.3.0/data/haarcascades/haarcascade_frontalface_default.xml"
eye_cascade = cv2.CascadeClassifier('/home/pi/opencv-3.3.0/data/haarcascades/haarcascade_eye.xml')
faceCascade = cv2.CascadeClassifier(cascadePath);

fn = input('Enter your Folder name: ')
os.system("mkdir "+fn)

vs = WebcamVideoStream(src=0).start()

while 1:
    time.sleep(0.05)
    frame = vs.read()
    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray, 1.1, 6)
    for (x,y,w,h) in faces:
        cv2.imwrite(fn+"/"+ datetime.now().strftime("%H:%M:%S.%f") + ".jpg", gray[y:y+h+30,x:x+w+20])
    cv2.imshow('frame',frame)
    key = cv2.waitKey(1) & 0xFF

Solution

  • In order to capture the head also you need to decrease the initial point where you start cropping the face.

    In your code you have used gray[y:y+h+30,x:x+w+20].

    • y takes into account the height of the cropped face. This is where you need to decrease the initial cropping point.
    • x denotes the width of the face which you do not need to change.

    Conclusion: Change it to gray[y-20:y+h, x:x+w] in line 22 within cv2.imwrite().