Search code examples
pythonpython-2.7numpyopencvface-detection

How to create a counter in face detection?


As you can see in the code below, it only detects the faces with haar cascade, I would like to know how I show the webcam how many people are currently detected. For example, show in the corner of the webcam X people detected.

from  __future__ import print_function 
import cv2 
cap = cv2.VideoCapture(0) 

face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

while (cap.isOpened()):
   ret,frame = cap.read()
   gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, 
flags=cv2.CASCADE_SCALE_IMAGE,minSize=(50, 50), maxSize=None)

if len(faces) > 0:
  print("detected person!")
for (x, y, w, h) in faces:
    cv2.rectangle(frame, (x - 10, y - 20), (x + w + 10, y + h + 10), (0, 255, 0), 2)
    roi_gray = frame[y-15:y + h+10, x-10:x + w+10]

cv2.imshow("imagem", frame) 
if cv2.waitKey(1) & 0xFF == ord('q'): 
break 

cap.release() 
cv2.destroyAllWindows()

Solution

  • Simply displaying the count of len(faces) may not solve the purpose,as you can have instances wherein there are multiple bounding boxes drawn over the same face.Therefore, I would suggest you to perform Non Maximal Suppression(NMS) on the result of your detections, followed by incrementing a counter for each time one calls the NMS operation. The final count of the counter will give you a better and more accurate result.