Created
June 16, 2021 14:51
-
-
Save sondt2709/38e26256cc5cb93e8adf1f643a37f721 to your computer and use it in GitHub Desktop.
Detect face from an image or RTSP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import time | |
import numpy as np | |
import asyncio | |
width, height = 640, 480 | |
cap = cv2.VideoCapture("rtsp://usr:pwd@localhost:554") | |
cap.set(3, width) | |
cap.set(4, height) | |
pTime = 0 | |
# Download and put the following file at same directory | |
# https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml | |
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') | |
while(1): | |
ret, frame = cap.read() | |
cTime = time.time() | |
fps = 1 / (cTime - pTime) | |
pTime = cTime | |
# Can use an image instead of RTSP frame | |
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
faces = faceCascade.detectMultiScale(gray, 1.1, 4) | |
for (x, y, w, h) in faces: | |
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2) | |
text = f'FPS: {int(fps)} | Have {len(faces)} people' | |
cv2.putText(frame, text, (40, 70), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255,0,0), 1) | |
cv2.imshow('VIDEO', frame) | |
# Press ESC to exit | |
k = cv2.waitKey(30) & 0xff | |
if k==27: | |
break | |
cap.release() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment