Ask Your Question

Face detection (haarcascade) OpenCV Python

asked 2015-06-06 05:44:51 -0500

Clyde gravatar image

updated 2015-06-07 04:03:51 -0500

Hello everyone, I have a little problem with my python program, in fact, I want to detect my face through the webcam of my laptop but the rectangle that should catch my face goes around the screen on its own, how can I solve this problem and allow my rectangle to catch only my face? Thank you, here it is the source code:

import numpy as np
import cv2
# import aprifile

istruzioni="Premi Esc per uscire"

cap = cv2.VideoCapture(0)

ret,frame =

r,h,c,w = 250,90,400,125
track_window = (c,r,w,h)

roi = frame[r:r+h, c:c+w]
hsv_roi =  cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))
roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180])

term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )

nomefile="haarcascade_frontalface_default.xml" # Name of the xml file
percorso="/home/matteo/opencv/opencv-2.4.9/data/haarcascades"+nomefile # Path

# aprifile.Inserisci_nome_file(nomefile) # Verifica l'esistenza del file

    ret ,frame =
    if ret == True:
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        dst = cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)

        ret, track_window = cv2.meanShift(dst, track_window, term_crit)

        fc = cv2.CascadeClassifier(percorso)

        # f = fc.detectMultiScale(frame, 1.3, 5, (30,30),
        f = fc.detectMultiScale(frame, 1.3, 5)

        x,y,w,h = track_window
        cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2)

        cv2.imshow('Rilevamento', frame)

        k = cv2.waitKey(60) & 0xff
        if k == 27:


edit retag flag offensive close merge delete


please add your code here (few folks will click dropbox links)

berak gravatar imageberak ( 2015-06-07 01:50:58 -0500 )edit

@berak, that was not that hard ^_^

StevenPuttemans gravatar imageStevenPuttemans ( 2015-06-07 04:04:21 -0500 )edit

dear @berak, @StevenPuttemans edited my question adding the code and deleting the dropbox link, now how can I solve my problem?

Clyde gravatar imageClyde ( 2015-06-07 09:28:30 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2015-06-08 03:38:24 -0500

hoju gravatar image

updated 2015-06-08 06:43:43 -0500

Your snippet tries to do more than detect the face. If just trying to get the box working I suggest you get a simple example working first, like this to put a box around the detected face:

import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
assert(not face_cascade.empty())
cam = cv2.VideoCapture(0)

ret = True
while ret:
    ret, img =
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    if 0xFF & cv2.waitKey(5) == 27:

edit flag offensive delete link more


I run your program but I can't see the rectangle around me

Clyde gravatar imageClyde ( 2015-06-08 04:38:04 -0500 )edit

You could start by making sure that the model is loaded and that a face is detected. Can you check those return values?

StevenPuttemans gravatar imageStevenPuttemans ( 2015-06-08 04:45:57 -0500 )edit

How can I check?

Clyde gravatar imageClyde ( 2015-06-08 05:26:37 -0500 )edit

Loading the cascade can silently fail if the file is not found. Can check with: assert(not face_cascade.empty()). I would prefer this raised an Exception when not found because it tripped me up a few times.

hoju gravatar imagehoju ( 2015-06-08 06:45:14 -0500 )edit

I've add assert but it returns a error: AssertionError

Clyde gravatar imageClyde ( 2015-06-08 12:37:36 -0500 )edit

Then your model is NOT correctly loaded!

StevenPuttemans gravatar imageStevenPuttemans ( 2015-06-09 02:45:26 -0500 )edit

And how can I load it correctly? EDIT: I add a for on cv2.rectangle -> for x,y,w,h in f: cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2) and It seems to work, but what if I want to do face recognition? I mean, after detecting my face, I want to compare it with some photos, if my face is the same of the photos it's OK, else the program returns an error message, do you have any ideas?

Clyde gravatar imageClyde ( 2015-06-09 09:08:56 -0500 )edit

Take a look at the facerecognizer class! Loading it correctly just means that you need to make sure your executable finds the file and that the assert is not generated!

StevenPuttemans gravatar imageStevenPuttemans ( 2015-06-10 04:13:26 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower


Asked: 2015-06-06 05:44:51 -0500

Seen: 422 times

Last updated: Jun 08 '15