Program suddenly close after running (opencv face-recognition)

156 Views Asked by At

Im trying to do a face-recognition using opencv I read some of the questions and I tried the answers below the questions on similiar topics but still the problem still persist The code that i've tried activates the webcam and in a second it stops working.

here' s my code

import cv2 as cv
import numpy as np
import face_recognition
import os, sys
from datetime import datetime
import datetime as dt
import math

def face_conf (face_distance, face_match_threshold=0.6):
    range = (1.0 - face_match_threshold)
    linear_val = (1.0 - face_distance) / (range * 2.0)

    if face_distance > face_match_threshold:
        return str(round(linear_val * 100, 2)) + '%'
    else:
        value = (linear_val + ((1.0 - linear_val) * math.pow((linear_val - 0.5) * 2, 0.2 ) )) * 100
        return str (round(value, 2)) + '%'


def markAttendance(name):

    with open ('FaceAttendance.csv','r+') as f:
        myList = f.readlines()
        nameList = []
        for line in myList:
            entry = line.split(',')
            nameList.append(entry[0])

        if name not in nameList:
            now = datetime.now()
            current_date = now.strftime('%B-%d-%Y')
            time_arr = dt.time(10, 30, 00)
            dateString = now.strftime('%H:%M:%S')
            time_arr_string = time_arr.strftime('%H:%M:%S')
            status_late = ('LATE')
            status_present = ('PRESENT')

            if dateString > time_arr_string:
                f.writelines(f'\n{name}, {dateString}, {current_date}, {status_late}')

            elif dateString < time_arr_string:
                f.writelines(f'\n{name}, {dateString}, {current_date}, {status_present}')



markAttendance('Attendance Start: ')

class FaceRecognition:

    face_locations = []
    face_encodings = []
    face_names = []
    knownFaceEncodings = []
    knownFaceNames = []
    process_current_frame = True

    def __init__(self):
        self.encode_faces()

    def encode_faces(self):
        for img in os.listdir('Attendance'):
            face_image = face_recognition.load_image_file(f'Attendance/{img}')
            face_encoding = face_recognition.face_encodings(face_image)[0]

            self.knownFaceEncodings.append(face_encoding)
            self.knownFaceNames.append(os.path.splitext(img)[0])

        print(self.knownFaceNames)

    def run_recognition(self):
        video_cap = cv.VideoCapture(0)

        if not video_cap.isOpened():
            sys.exit('Error: Video Not Found!')

        while True:
            ret, frame = video_cap.read()

            if self.process_current_frame:
                small_frame = cv.resize(frame, (0,0), fx=0.25, fy=0.25)
                rgb_small_frame = small_frame [:, :, ::-1]

                #Find the face in current frame
                self.face_locations = face_recognition.face_locations(rgb_small_frame)
                self.face_encodings = face_recognition.face_encodings(rgb_small_frame, self.face_locations)

                self.face_names = []
                for face_encoding in self.face_encodings:
                    matches = face_recognition.compare_faces(self.knownFaceEncodings, face_encoding)
                    name = 'Unknown'
                    confidence = 'Unknown'

                    face_distances = face_recognition.face_distance(self.knownFaceEncodings, face_encoding)
                    matchIndex = np.argmin(face_distances)

                    if matches[matchIndex]:
                        name = self.knownFaceNames[matchIndex]
                        confidence = face_conf(face_distances[matchIndex])
                        markAttendance(name)


                    self.face_names.append(f'{name} ({confidence})')

            self.process_current_frame = not self.process_current_frame

            #display annotations

            for (top, right, bottom, left), name in zip (self.face_locations, self.face_names):
                top *=4
                right *= 4
                bottom *= 4
                left *= 4


                cv.rectangle (frame, (left, top), (right, bottom), (0, 255, 0), 2)
                cv.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), -1)
                cv.putText(frame, name, (left + 6, bottom - 6), cv.FONT_HERSHEY_COMPLEX, .75, (255, 255, 255), 2)


            cv.imshow ('Face Recognition', frame)
            if cv.waitKey(1) & 0xFF == ord('s'):
                break

        video_cap.release()
        cv.destroyAllWindows()


if __name__ == '__main__':
    fr = FaceRecognition()
    fr.run_recognition()

THIS WILL SHOW WHEN IT SUDDENLY CLOSE Process finished with exit code -1073741819 (0xC0000005)

1

There are 1 best solutions below

1
abdoalaasadik On

I fixed that problem after many tries. The actual problem is that the RBG did not get converted correctly in the while loop.

Change: rgb_small_frame = small_frame[:, :, ::-1]
To: rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)

It worked with me after doing this change!