[Python] close the webcam and keep running the program [duplicate]

Discussão em 'Python' iniciado por Stack, Dezembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to turn off the webcam and start the other function, but when I try to do that, it keeps giving me an error and the other functions couldn't work. Here's the code.

    import matplotlib.pyplot as plt
    import numpy as np
    import cv2
    import time

    cap = cv2.VideoCapture(0)
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

    def eye_detector():
    while True:
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
    roi_gray = gray[y:y + w, x:x + w]
    roi_color = frame[y:y + h, x:x + w]
    eyes = eye_cascade.detectMultiScale(roi_gray, 1.3, 5 )

    for (ex, ey, ew, eh) in eyes:
    cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 5)

    cv2.imshow('frame', frame)

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

    elif len(faces) >0 and (x == 210, y ==140):
    time.sleep(10)
    cap.release()
    plt.show()

    cap.release()
    cv2.destroyAllWindows()


    Here's the error Traceback (most recent call last): File "c:\project_ANNIE\project1.py", line 24, in <module> project1_module2.eye_detector() File "c:\project_ANNIE\project1_module2.py", line 14, in eye_detector gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cv2.error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:196: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

    I expected it to turn off the camera and start the next function, but it didn't. The camera wasn't turned off, and the next function didn't work. I need help.

    Continue reading...

Compartilhe esta Página