Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
Code:
#!/usr/bin/env python37
#Raspberry pi 3B/3B+, 4B, Buster, OpenCV 4.2.0
#Date: 5th Apriol, 2020

import numpy as np
import cv2
from datetime import datetime

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
fourcc = cv2.VideoWriter_fourcc(*'XVID')  
out = cv2.VideoWriter('face_detection.avi', fourcc, 10.0, (640, 480))
font = cv2.FONT_HERSHEY_SIMPLEX

cap = cv2.VideoCapture(0)

while cap.isOpened():
    date_time = str(datetime.today().strftime("%d-%m-%Y")
                    + '                '
                    + str(datetime.now().strftime("%H:%M:%S")))

    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(frame, (x, y),(x+w, y+h),(255, 0, 0), 2)

    out.write(frame)
    cv2.putText(frame, date_time, (30, 400), font, 1,
                (0, 0, 255), 2, cv2.LINE_AA)

    cv2.imshow('img', frame)
    k = cv2.waitKey(1)  
    if k is 27:
        break

cap.release()
cv2.destroyAllWindows()

In line 32, I change == to is operator for python 3.7 or later. You may used == if its doesn't work.