Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

This snippet tries to do more that detect face. If 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')
cam = cv2.VideoCapture(0)

ret = True
while ret:
    ret, img = cam.read()
    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)
    cv2.imshow('img',img)
    if 0xFF & cv2.waitKey(5) == 27:
        break

cv2.destroyAllWindows()

This Your snippet tries to do more that 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')
cam = cv2.VideoCapture(0)

ret = True
while ret:
    ret, img = cam.read()
    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)
    cv2.imshow('img',img)
    if 0xFF & cv2.waitKey(5) == 27:
        break

cv2.destroyAllWindows()

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 = cam.read()
    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)
    cv2.imshow('img',img)
    if 0xFF & cv2.waitKey(5) == 27:
        break

cv2.destroyAllWindows()