python – How to create a counter in face detection?

Question:

As you can see in the code below, it only detects faces with haar cascade, I would like to know how I can display on the webcam the amount of people detected at the moment.

from  __future__ import print_function #importa a funcao da biblioteca future
import cv2 
cap = cv2.VideoCapture(0) #webcam

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

while (cap.isOpened()):
ret,frame = cap.read()
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) #faz a conversao pra cinza por ser mais leve pro pc
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("Pessoa detectada!")
    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) #mostra a face detectada
if cv2.waitKey(1) & 0xFF == ord('q'): # q definido para sair do projeto
    break #para o programa

cap.release() #mostra as coordenadas da deteccao
cv2.destroyAllWindows()

Answer:

I believe this is what you are looking for…

text = "{} face(s) found".format(len(faces))
cv2.putText(frame, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX,
    0.5, (0, 0, 255), 2)
Scroll to Top