【问题标题】:Return True if the face is detected at least for 3 seconds如果检测到面部至少 3 秒,则返回 True
【发布时间】:2022-01-20 11:45:07
【问题描述】:

如何让网络摄像头保持打开状态,并在几秒钟内使用 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")

【问题讨论】:

  • 使用变量作为累加器。如果您检测到面部,则将其递增,如果未将其设置为 0。那么,如果变量达到某个阈值,则意味着您已经连续 n 次检测面部。如果您知道每次读数需要多少时间,您可以调整阈值,因此连续读数意味着 3 秒。这样您就不需要延迟,并且视频源不会变得生涩。
  • 您不需要在文本中添加
    。要将文本换行,只需用新行分隔文本即可。
  • @SembeiNorimaki 我已经想到了类似的解决方案,但是代码会在不同的PC上运行,因此执行速度会有所不同
  • 然后使用时间库,保存第一次检测时的时间戳,然后在每次检测时检查是否有足够的时间将连续检测视为阳性。

标签: python opencv face-detection haar-classifier


【解决方案1】:

只记录检测到人脸的时间,仅当检测到人脸并且当前时间戳为记录的时间戳后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")

【讨论】:

    猜你喜欢
    • 2013-06-04
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多