CV2: закрытие подключения камеры и повторное открытие в другой функции - PullRequest
0 голосов
/ 08 ноября 2018

Так что в основном у меня есть две функции в этом скрипте. 1 Выполняет распознавание лиц и отображает данные, хранящиеся в базе данных, вторая срабатывает, когда видит лицо, которое не распознает, и сохраняет временные данные. Проблема в том, что при запуске второго я постоянно получаю сообщение об ошибке

VIDEOIO ERROR не может открыть камеру по индексу 1

Невозможно остановить поток: устройство или ресурс занят

Я почти уверен, что правильно выпустил его в функции face_recog, но я не уверен. Любая помощь приветствуется.

video_capture = cv2.VideoCapture(1)

configured_datetime = str(datetime.datetime.now().strftime('%c'))

def gather_data():

    faceDetect1=cv2.CascadeClassifier('frontal_cascade_improved.xml')
    faceDetect2=cv2.CascadeClassifier('profilecascade.xml')



 # #Input Info
    # name = input('Input Name:  ')
    # position = input('Position/Title:  ')

    # Generate info later
    name = 'Uknown Entity ' + ' Seen ' + configured_datetime
    position = 'Unknown Position'

    directory_path = (path + '/' + name)
    os.makedirs(directory_path, exist_ok=True)
    sampleNum = 0

    while(True):
        video_capture = cv2.VideoCapture(1)
        ret,img=video_capture.read()
        # gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        faces=faceDetect1.detectMultiScale(img)
        for(x,y,w,h) in faces:
            sampleNum=sampleNum+1;
            cv2.imwrite(directory_path + '/' + str(name) + '.' + str(sampleNum) +'.jpg', img)
            cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
            cv2.waitKey(100);
            cv2.imshow("Face",img);
            cv2.waitKey(1);
        if(sampleNum>6):
            break;
    database_info = Faces(name=name, image_repository=str(directory_path), position=position)
    db.session.add(database_info)
    db.session.commit()
    video_capture.release()
    cv2.destroyAllWindows()


def face_recog():


 # try:

    image_info = Faces.query.all()
    known_face_encodings = []
    known_face_names = []

    #manually set number of images, make it match sampleNum - more images DOESN'T increase recognizability---

    for num, person in enumerate(image_info, 1):
        # Go thru all iamges - doesn't improve recog
        # for i, x in enumerate(range(6), 1):
        image_file = str('datasets/' + person.name + '/' + person.name + '.' + str(1) + '.jpg')
        print(image_file)
        image_base = face_recognition.load_image_file(image_file)
        image_encoding = face_recognition.face_encodings(image_base)[0]
        known_face_encodings.append(image_encoding)
        known_face_names.append(person.name)

    # Initialize some variables
    face_locations = []
    face_encodings = []
    face_names = []
    process_this_frame = True

    while True:
        image_info = Faces.query.all()
        # Grab a single frame of video
        ret, frame = video_capture.read()

        # Resize frame of video to 1/4 size for faster face recognition processing
        # small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

        # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
        rgb_small_frame = frame

        # Only process every other frame of video to save time
        if process_this_frame:
            # Find all the faces and face encodings in the current frame of video
            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:
                # See if the face is a match for the known face(s)
                matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                name = "Unknown"

                # If a match was found in known_face_encodings, just use the firsst one.
                if True in matches:
                    first_match_index = matches.index(True)
                    name = known_face_names[first_match_index]

                face_names.append(name)

        process_this_frame = not process_this_frame


        # Display the results
        for (top, right, bottom, left), name in zip(face_locations, face_names):
            # Scale back up face locations since the frame we detected in was scaled to 1/4 size
            top *= 1
            right *= 1
            bottom *= 1
            left *= 1


            if name == 'Unknown':
                video_capture.release()
                gather_data()
            elif 'Entity' in name:
                cv2.rectangle(frame, (left, top), (right, bottom), (19, 198, 192), 2)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, name, (left + 30, bottom + 20), font, 0.5, (0, 0, 0), 3)
                cv2.putText(frame, name, (left + 30, bottom + 20), font, 0.5, (19, 198, 192), 1)
            else:
                person = Faces.query.filter_by(name=name).first()
                # Draw a box around the face
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
                # Draw a label and text
                cv2.rectangle(frame, (left, bottom - 12), (right, bottom), (0,255, 0), cv2.FILLED)
                font = cv2.FONT_HERSHEY_DUPLEX
                cv2.putText(frame, name, (left - 7, bottom + 20), font, 0.75, (0, 0, 0), 3)
                cv2.putText(frame, name, (left - 7, bottom + 20), font, 0.75, (255, 255, 255), 1)
                cv2.putText(frame, person.position, (left - 7, bottom + 45), font, 0.75, (0, 0, 0), 3)
                cv2.putText(frame, person.position, (left - 7, bottom + 45), font, 0.75, (255, 255, 255), 1)


        # Display the resulting image
        cv2.imshow('Video', frame)

        # Hit 'q' on the keyboard to quit!
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release handle to the webcam
    video_capture.release()
    cv2.destroyAllWindows()

Редактировать: Исправлено форматирование и просто хотелось добавить, что при тестировании различных вещей есть лишний код, но кроме передачи использования камеры, он работает.

1 Ответ

0 голосов
/ 08 ноября 2018

Решил проблему, передав переменную video_capture в collect_data из функции face_recog. Таким образом, все ссылки на фактическое видеоустройство исчезли, кроме как внутри face_recog. И один раздел выглядит как ..

if name == 'Unknown':
    gather_data(video_capture)

Редактировать: О, и я просто снова вызываю face_recog () в конце collect_data

...