执行后 10 秒打破 while 循环

Break the while loop 10 seconds after executed

我使用 face_recognition 和 OpenCV 库制作了人脸识别应用程序,但我想在执行脚本 10 秒后中断 while 循环。由于 fps 较低,我无法使用 OpenCV 的 waitKey(10000)。我怎样才能做到这一点?谢谢。

While 循环是;

flag = True 

while flag:

    # ********** FACE RECOGNITION PART START **********
    ret, frame = video_capture.read()
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    rgb_small_frame = small_frame[:, :, ::-1]

    if process_this_frame:
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]
                empID = employeeID[best_match_index]
                empFNAME = employeeFirstName[best_match_index]
                empLNAME = employeeLastName[best_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame
    # ********** FACE RECOGNITION PART END **********

    # ********** FACE VISUALIZATION PART START **********
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
    # ********** FACE VISUALIZATION PART END **********

    cv2.imshow('Video', frame)
    
    # ********** QR CODE PART START **********
    _, img = video_capture.read()
    data, bbox, _ = qrDetector.detectAndDecode(img)
    if data:
        a=data
        print(str(a))

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    # ********** QR CODE PART END **********

video_capture.release()
cv2.destroyAllWindows()

我试过这些来打破循环;

时间模块

starting_time = time.time()

while flag:
    ///
    ///
    ending_time = time.time()
    if ending_time - starting_time == 10:
        break

按键

from pynput.keyboard import Key, Controller
keyboard = Controller()

while flag:
    ///
    ///
    keyboard.press('q')
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
keyboard.release('q')

当我尝试时间模块时,OpenCV 屏幕冻结并停止工作,按键根本不起作用。

就几句话,抱歉:使用 datetime 和 timedelta

from datetime import datetime, timedelta
...

loop_start_moment = datetime.now()
while ...:
    # loop body
    if datetime.now() - loop_start_moment > timedelta(seconds=10):
        break