Q:

CV2: Closing camera connection and reopening in different function

So basically I have two functions in this script. 1 Does face recognition and displays data stored in a database, the second is triggered when it sees a face that it doesn't recognize, and stores temp data. The issue is, when the second one is triggered, I consistently get the error

VIDEOIO ERROR can't open camera by index 1
Unable to stop the stream: Device or resource busy

I'm pretty sure I'm releasing it properly in the face_recog function but I'm not sure. Any help is appreciated.
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()

Edit: Fixed formatting and just wanted to add that there is superfluous code from testing various things but other than passing the usage of the camera, it works.

A:

Solved the issue by passing in the video_capture variable to gather_data from face_recog function. So all references to the actual video device are gone except from inside face_recog. And the one section looks like..
if name == 'Unknown':
    gather_data(video_capture)

Edit: Oh, and I'm just calling face_recog() again at the end of gather_data

