I am currently trying to detect face from my laptop camera but for some reason the code I found is not giving a result. The code is starting the webcam and not giving any errors but no rectangles are drawn for the faces. No faces are being detected hence the for loop is never running, I tried changing the scale factor but that did not help. Both the xml files are in the same folder as the code. The code is as following:
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.VideoCapture(0)
while(1):
_,f=img.read()
gray = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(f,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = f[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',f)
if cv2.waitKey(25) == 27:
break
cv2.destroyAllWindows()
img.release()
Hello your program work fine, You have 2 small problems one you need Tab this code to put inside the while:
cv2.imshow('img',f)
if cv2.waitKey(25) == 27:
break
And be sure the your xml files are founded this is my code:
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv3/3.0.0/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv3/3.0.0/share/OpenCV/haarcascades/haarcascade_eye.xml')
img = cv2.VideoCapture(0)
while(1):
_,f=img.read()
gray = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(f,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = f[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('Test',f)
if cv2.waitKey(25) == 27:
break
cv2.destroyAllWindows()
img.release()