freezing in opencv(windows 11)

Viewed 33

I have a webcam application that has a model that predicts whether eyes are open or closed. It runs but the video capture is very slow and sometimes the camera window crashes entirely. At times the video runs smoothly but after a couple of freezes from time to time. Here is the code:

cap = cv2.VideoCapture(0)
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print(cap.get(cv2.CAP_PROP_FPS))

if not cap.isOpened():
    raise IOError('Cannot open webcam')
counter = 0

# create a while loop that runs while webcam is in use

while True:

    #creating a while loop that runs when webcam is in use

    ret, frame = cap.read()

    # use only every other frame to manage speed and memory usage

    frame_count = 0
    if frame_count == 0:
        frame_count += 1
        pass
    else:
        count = 0
        continue

    # function called on the frame

    image_for_prediction = eye_cropper(frame)
    try:
        image_for_prediction = image_for_prediction/255.0
    except:
        continue

    # get prediction from model

    prediction = eye_model.predict(image_for_prediction)

    # Based on prediction, display either "Open Eyes" or "Closed Eyes"

    if prediction < 0.5:
        counter = 0
        status = 'Open'
        cv2.putText(frame, status, (round(w/2)-80,70), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,0), 2, cv2.LINE_4)

    else:
        counter = counter + 1
        status = 'Closed'
        cv2.putText(frame, status, (round(w/2)-104,70), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,0,255), 2, cv2.LINE_4)
       
        # if the counter is greater than 3, play and show alert that user is asleep

        if counter > 2:
            cv2.putText(frame, 'DRIVER SLEEPING', (round(w/2)-136,round(h) - 146), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 2, cv2.LINE_4)
            cv2.imshow('Drowsiness Detection', frame)
            k = cv2.waitKey(1)
            playsound('rooster.mov')
            counter = 1
            continue
    cv2.imshow('Drowsiness Detection', frame)
    k = cv2.waitKey(1)
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
0 Answers
Related