如何讓網路攝像頭保持打開狀態并僅使用 haar 級聯進行面部檢測幾秒鐘?
我有一個函式,如果已經執行了人臉檢測,此函式回傳 true,但它不能在檢測到后立即執行,而必須至少在檢測到人臉后執行以 3 秒為例。
如果我使用時間模塊并等待,顯然這只會減慢我的程式的執行速度,因此也會減慢cv2.VideoCapture,看到生澀的網路攝像頭。
這是代碼:
import cv2
def face_detect():
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frames = video_capture.read()
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frames, (x, y), (x w, y h), (0, 255, 0), 2)
return True
if __name__ == '__main__':
detected = face_detect()
if detected == True:
print("The face is detected. OK")
else:
print("I'm sorry but I can't detect your face")
uj5u.com熱心網友回復:
檢測到面部時,簡單地記錄時間,看到只有當檢測到面部畫臉和當前時間戳timeout記錄時間戳后秒。
import cv2
from time import time
def face_detect(timeout):
video_capture = cv2.VideoCapture(0)
start_time = 0 # Temporary value.
face_detected = False # Used to see if we've detected the face.
while True:
# Capture frame-by-frame
ret, frames = video_capture.read()
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
if not face_detected and faces:
face_detected = True
start_time = time()
elif not faces:
face_detected = False # Reset if we don't find the faces.
elif face_detected and time() - start_time >= timeout:
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frames, (x, y), (x w, y h), (0, 255, 0), 2)
return True
if __name__ == '__main__':
detected = face_detect(timeout=3)
if detected == True:
print("The face is detected. OK")
else:
print("I'm sorry but I can't detect your face")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/387267.html
標籤:Python opencv 人脸检测 haar-分类器
上一篇:查找覆寫原始矩形的旋轉矩形的大小
