OpenCV面对presence/absence个时间段

OpenCV face presence/absence periods of time

有一个代码可以在视频文件中逐帧显示时检测人脸:

cap = cv2.VideoCapture(videoPath)
faceCascade = cv2.CascadeClassifier(cascPath)

while (cap.isOpened()):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, 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(frame, (x, y), (x+w, y+h), (233, 153, 22), 2)

    # Display the resulting frame
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

我需要一个代码,可以为您提供检测到人脸的时间段和未检测到人脸的时间段。有人可以帮我吗?至少有一些提示如何解决这个问题,在哪里看等等。

跟踪当前帧、前一帧和包含人脸的当前序列的起始帧的时间戳。

一旦您不再在框架中检测到人脸,请将一对 (starting, previous) 添加到列表中。

import time

# ....

def get_timestamp():
    # Make the timestamp whatever you want...
    return time.strftime("%Y%m%d-%H%M%S")

# ....

face_present = []
ts_start = None
ts_prev = None

# ....

while (cap.isOpened()):
    ret, frame = cap.read()
    ts = get_timestamp()

    # ....

    if len(faces) > 0: # Some faces detected
        if ts_start is None: # This is the start of current sequence
            ts_start = ts
    elif (ts_start is not None) and (ts_prev is not None):
        # First frame without face following a sequence with face...
        face_present.append((ts_start, ts_prev))
        ts_start = None

    ts_prev = ts

您可以随意设置时间戳,如果您想要的话,甚至可以是帧号。

同样的方法也可以判断人脸不存在的次数,只需要改变第一个if语句的条件即可。