예제 #1
0
def add_person(people_folder, shape):
    """ Funtion to add pictures of a person

    :param people_folder: relative path to save the person's pictures in
    :param shape: Shape to cut the faces on the captured images:
                  "rectangle" or "ellipse"
    :type people_folder: String
    :type shape: String
    """
    person_name = raw_input('What is the name of the new person: ').lower()
    folder = people_folder + person_name
    if not os.path.exists(folder):
        raw_input("I will now take 20 pictures. Press ENTER when ready.")
        os.mkdir(folder)
        video = VideoCamera()
        detector = FaceDetector('face_recognition_system/frontal_face.xml')
        counter = 1
        timer = 0
        cv2.namedWindow('Video Feed', cv2.WINDOW_AUTOSIZE)
        cv2.namedWindow('Saved Face', cv2.WINDOW_NORMAL)
        while counter < 21:
            frame = video.get_frame()
            face_coord = detector.detect(frame)
            if len(face_coord):
                frame, face_img = get_images(frame, face_coord, shape)
                # save a face every second, we start from an offset '5' because
                # the first frame of the camera gets very high intensity
                # readings.
                if timer % 100 == 5:
                    cv2.imwrite(folder + '/' + str(counter) + '.jpg',
                                face_img[0])
                    print("Images Saved: " + str(counter))
                    counter += 1
                    cv2.imshow('Saved Face', face_img[0])

            cv2.imshow('Video Feed', frame)
            cv2.waitKey(50)
            timer += 5
    else:
        print "This name already exists."
        sys.exit()
예제 #2
0
def add_person(people_folder, shape):
    """ Funtion to add pictures of a person

    :param people_folder: relative path to save the person's pictures in
    :param shape: Shape to cut the faces on the captured images:
                  "rectangle" or "ellipse"
    :type people_folder: String
    :type shape: String
    """
    person_name = input('What is the name of the new person: ').lower()
    folder = people_folder + person_name
    if not os.path.exists(folder):
        input("I will now take 20 pictures. Press ENTER when ready.")
        os.mkdir(folder)
        video = VideoCamera()
        detector = FaceDetector('face_recognition_system/frontal_face.xml')
        counter = 1
        timer = 0
        cv2.namedWindow('Video Feed', cv2.WINDOW_AUTOSIZE)
        cv2.namedWindow('Saved Face', cv2.WINDOW_NORMAL)
        while counter < 21:
            frame = video.get_frame()
            face_coord = detector.detect(frame)
            if len(face_coord):
                frame, face_img = get_images(frame, face_coord, shape)
                # save a face every second, we start from an offset '5' because
                # the first frame of the camera gets very high intensity
                # readings.
                if timer % 100 == 5:
                    cv2.imwrite(folder + '/' + str(counter) + '.jpg',
                                face_img[0])
                    print( 'Images Saved:' + str(counter))
                    counter += 1
                    cv2.imshow('Saved Face', face_img[0])

            cv2.imshow('Video Feed', frame)
            cv2.waitKey(50)
            timer += 5
    else:
        print( "This name already exists.")
        sys.exit()
예제 #3
0
def add_person_from_file(people_folder, shape):
    """ Funtion to add pictures of a person
        
        :param people_folder: relative path to save the person's pictures in
        :param shape: Shape to cut the faces on the captured images:
        "rectangle" or "ellipse"
        :type people_folder: String
        :type shape: String
        """
    person_name = "Irshan"
    folder = people_folder + person_name
    os.mkdir(folder)
    folderSample = people_folder + "IrshanSample"

    detector = FaceDetector('face_recognition_system/frontal_face.xml')
    counter = 1
    timer = 0
    cv2.namedWindow('Video Feed', cv2.WINDOW_AUTOSIZE)
    cv2.namedWindow('Saved Face', cv2.WINDOW_NORMAL)

    for filename in os.listdir(folderSample):
        imgFrame = cv2.imread(os.path.join(folderSample,filename),0)
        print("FileName",os.path.join(folderSample,filename))
        face_coord = detector.detect(imgFrame)
        print(len(face_coord))
        if len(face_coord):
            imgFrame, face_img = get_images_fromfile(imgFrame, face_coord, shape)
            print(face_img)
            # save a face every second, we start from an offset '5' because
            # the first frame of the camera gets very high intensity
            # readings.
            cv2.imwrite(folder + '/' + str(counter) + '.jpg',
                        face_img[0])
            counter += 1
            print ('Images Saved:' + str(counter))
            cv2.imshow('Saved Face', face_img[0])
                    
        cv2.imshow('Video Feed', imgFrame)
        cv2.waitKey(1)
        timer += 5
예제 #4
0
def recognize_people(people_folder, shape):
    """ Start recognizing people in a live stream with your webcam

    :param people_folder: relative path to save the person's pictures in
    :param shape: Shape to cut the faces on the captured images:
                  "rectangle" or "ellipse"
    :type people_folder: String
    :type shape: String
    """
    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print "Have you added at least one person to the system?"
        sys.exit()
    print "This are the people in the Recognition System:"
    for person in people:
        print "-" + person

    print 30 * '-'
    print "   POSSIBLE RECOGNIZERS TO USE"
    print 30 * '-'
    print "1. EigenFaces"
    print "2. FisherFaces"
    print "3. LBPHFaces"
    print 30 * '-'

    choice = check_choice()

    detector = FaceDetector('face_recognition_system/frontal_face.xml')
    if choice == 1:
        recognizer = cv2.face.EigenFaceRecognizer_create()
        threshold = 4000
    elif choice == 2:
        recognizer = cv2.face.FisherFaceRecognizer_create()
        threshold = 300
    elif choice == 3:
        recognizer = cv2.face.LBPHFaceRecognizer_create()
        threshold = 105
    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + '/' + image, 0))
            labels.append(i)
    try:
        recognizer.train(images, np.array(labels))
    except:
        print "\nOpenCV Error: Do you have at least two people in the database?\n"
        sys.exit()

    video = VideoCamera()
    while True:
        frame = video.get_frame()
        faces_coord = detector.detect(frame, False)
        if len(faces_coord):
            frame, faces_img = get_images(frame, faces_coord, shape)
            for i, face_img in enumerate(faces_img):
                if __version__ == "3.1.0":
                    collector = cv2.face.MinDistancePredictCollector()
                    recognizer.predict(face_img, collector)
                    conf = collector.getDist()
                    pred = collector.getLabel()
                else:
                    pred, conf = recognizer.predict(face_img)
                print "Prediction: " + str(pred)
                print 'Confidence: ' + str(round(conf))
                print 'Threshold: ' + str(threshold)
                if conf < threshold:
                    cv2.putText(frame, labels_people[pred].capitalize(),
                                (faces_coord[i][0], faces_coord[i][1] - 2),
                                cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                cv2.LINE_AA)
                else:
                    cv2.putText(frame, "Unknown",
                                (faces_coord[i][0], faces_coord[i][1]),
                                cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                cv2.LINE_AA)

        cv2.putText(frame, "ESC to exit", (5, frame.shape[0] - 5),
                    cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2, cv2.LINE_AA)
        cv2.imshow('Video', frame)
        if cv2.waitKey(100) & 0xFF == 27:
            sys.exit()
예제 #5
0
def func_addpersonpics(folder, shape):
    count = 0
    mkdir('data/pics')
    mkdir('data/pos')
    try:
        file_images = raw_input("Enter the images' direction: ")
    except:
        print("NO FOUND FOLDER !!!")
        sys.exit()
    cascade_faces = [
        "haarcascade_frontalface_default.xml",
        "haarcascade_frontalface_alt.xml", "haarcascade_frontalface_alt2.xml",
        "haarcascade_frontalface_alt_tree.xml", "haarcascade_profileface.xml"
    ]

    #copy file to pics folder
    print("Copying images .....")
    for file_type in [file_images]:
        for img in os.listdir(file_type):
            imagePath = file_type + '/' + img
            newimagePath = "data/pics/" + img
            shutil.copy2(imagePath, newimagePath)
    print("Complete to copy images")
    processpercent = 0
    print("Faces detecing ..... " + str(processpercent) + "%")

    for i in cascade_faces:
        cascadePath = "haarcascade/" + i
        #print (cascadePath)
        detector = FaceDetector(cascadePath)
        for file_type in ['data/pics']:
            for img in os.listdir(file_type):
                imagePath = file_type + '/' + img
                frame = cv2.imread(imagePath)
                face_coord = detector.detect(frame)
                if len(face_coord):
                    frame, face_img = get_images(frame, face_coord, shape)
                    now = datetime.datetime.now()
                    #cv2.imwrite(folder + '/' + img, face_img[0])

                    #after create new function detect faces, will delete this line
                    cv2.imwrite('data/crop/' + img, face_img[0])

                    print("Images Saved: " + img)
                    cv2.imshow("frame after", cv2.resize(frame, (240, 320)))
                    cv2.waitKey(100)
                    count += 1
                    #copy to pos
                    newimagePath = "data/pos/" + img
                    shutil.move(imagePath, newimagePath)
        processpercent += 20
        print("Faces detecing ..... " + str(processpercent) + "%")

    #os.rmdir()
    #shutil.rmtree()

    while True:
        ans = raw_input("Do you want add more? (y/n)")
        if (ans == "y"):
            func_addpersonpics(folder, shape)
        else:
            sys.exit()
def recognize_people(people_folder, shape, netcam):
    """ Start recognizing people in a live stream with your webcam

    :param people_folder: relative path to save the person's pictures in
    :param shape: Shape to cut the faces on the captured images:
                  "rectangle" or "ellipse"
    :type people_folder: String
    :type shape: String
    """
    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print("Have you added at least one person to the system?")
        sys.exit()
    print("This are the people in the Recognition System:")
    for i, person in enumerate(people):
        iplus = i + 1
        if (iplus < len(people)):
            print(str(i + 1) + "- " + person + ",")
            iplus += 1
        elif (iplus == len(people)):
            print(str(i + 1) + "- " + person)

    detector = FaceDetector('face_recognition_system/frontal_face.xml')

    recognizer = cv2.face.createLBPHFaceRecognizer()

    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + '/' + image, 0))
            labels.append(i)
    try:
        recognizer.train(images, np.array(labels))
    except:
        print(
            "\nOpenCV Error: Image Dimension Problems or you dont have at least two people in the database\n"
        )
        #sys.exit()
        cv2.waitKey(100)

    video = VideoCamera(netcam)
    k = 1
    threshsum = 0
    data = []
    f = open("predictdata.txt", "w+")

    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    localtime = time.asctime(time.localtime(time.time()))
    l = ''.join(e for e in localtime if e.isalnum())
    out = cv2.VideoWriter(l + '.avi', fourcc, 20.0, (640, 480))

    while True:
        frame = video.get_frame()
        faces_coord = detector.detect(frame, True)
        if len(faces_coord):
            [frame, faces_img] = get_images(frame, faces_coord, shape)
            for i, face_img in enumerate(faces_img):
                if (__version__ == "3.1.0"):
                    collector = cv2.face.MinDistancePredictCollector()
                    recognizer.predict(face_img, collector)
                    conf = collector.getDist()
                    pred = collector.getLabel()
                else:
                    [pred, conf] = recognizer.predict(face_img)
                print("Prediction: " + str(pred))
                print('Confidence: ' + str(round(conf)))
                avg = 20
                if (k <= avg):
                    threshsum = conf + threshsum
                    threshold = 150
                    k = k + 1
                else:
                    threshold = threshsum / (avg - 1)
                print('Threshold Used: ' + str(threshold))
                print("k val: " + str(k))
                print("threshsum: " + str(threshsum))
                if (conf <= threshold and k > avg):
                    cv2.putText(frame,
                                'Pred => ' + labels_people[pred].capitalize(),
                                (faces_coord[i][0], faces_coord[i][1] - 2),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255),
                                1, cv2.LINE_AA)
                    data.append(pred)
                    f.write("%d\n" % (pred))
                elif (k <= avg):
                    cv2.putText(frame, "Finding Threshold",
                                (faces_coord[i][0], faces_coord[i][1]),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0),
                                1, cv2.LINE_AA)
                elif (conf >= threshold and k > avg):
                    cv2.putText(frame, "Face Unknown",
                                (faces_coord[i][0], faces_coord[i][1]),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2,
                                cv2.LINE_AA)
                    dat = 'NaN'
                    data.append(dat)
                    f.write("%s\n" % (dat))
        print('Appended Data: ' + str(data))
        cv2.putText(frame, "Press ESC to Exit", (5, frame.shape[0] - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1, cv2.LINE_AA)
        if len(frame):
            # write the flipped frame
            out.write(frame)
            cv2.putText(frame, "Recording...", (490, frame.shape[0] - 420),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2,
                        cv2.LINE_AA)
        cv2.imshow('Video Feed', frame)
        if cv2.waitKey(100) & 0xFF == 27:
            f.close()
            out.release()
            cv2.destroyAllWindows()
            sys.exit()
예제 #7
0
def recognize_people(people_folder, shape, detection_mode):
    """ Start recognizing people in a live stream with your webcam
    """
    fingerprint_retries = []
    counter = 1
    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print("Have you added at least one person to the system?")
        sys.exit()
    print("This are the people in the Recognition System:")
    for person in people:
        print("-" + person)

    print(30 * '-')

    detector = FaceDetector('face_recognition_system/frontal_face.xml')

    recognizer = cv2.face.EigenFaceRecognizer_create()
    threshold = 4000
    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + '/' + image, 0))
            labels.append(i)
    try:
        recognizer.train(images, np.array(labels))
    except:
        print(
            "\nOpenCV Error: Do you have at least two people in the database?\n"
        )
        sys.exit()

    video = VideoCamera()
    while True:
        frame = video.get_frame()
        frame = cv2.flip(frame, -1)
        cv2.imwrite("2.jpg", frame)
        faces_coord = detector.detect(frame, False)
        if len(faces_coord):
            frame, faces_img = get_images(frame, faces_coord, shape)
            for i, face_img in enumerate(faces_img):
                if __version__ == "3.1.0":
                    collector = cv2.face.MinDistancePredictCollector()
                    recognizer.predict(face_img, collector)
                    conf = collector.getDist()
                    pred = collector.getLabel()
                else:
                    pred, conf = recognizer.predict(face_img)
                print("Prediction: " + str(pred))
                #print ('Confidence: ' + str(round(conf)))
                #print ('Threshold: ' + str(threshold))
                if conf < threshold:
                    cv2.putText(frame, labels_people[pred].capitalize(),
                                (faces_coord[i][0], faces_coord[i][1] - 2),
                                cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255),
                                1, cv2.LINE_AA)
                    if detection_mode == 'door_lock':
                        print('Accessing as ' + labels_people[pred] + '......')
                        print('Please verify yourself with fingerprint...')
                        fingerprint_label = recognize_finger()
                        if (int(fingerprint_label) == int(pred)):
                            #print (int(pred))
                            print('Access granted...')
                            print('Unlocking door....')
                            GPIO.output(14, True)
                            GPIO.output(24, False)
                            buzzer_success()
                            time.sleep(5)
                            GPIO.output(24, True)
                            GPIO.output(14, False)
                            print('Door Unlocked!')
                            now = datetime.now()
                            now_string = now.strftime("%d/%m/%Y %H:%M:%S")
                            with open('door_unlock_data.csv',
                                      mode='a') as door_data:
                                door_writer = csv.writer(
                                    door_data,
                                    delimiter=',',
                                    quotechar='"',
                                    quoting=csv.QUOTE_MINIMAL)
                                door_writer.writerow([
                                    str(counter),
                                    str(pred),
                                    str(labels_people[pred]),
                                    str(now_string)
                                ])
                            counter += 1
                        else:
                            #print (int(pred))
                            fingerprint_retries.append(labels_people[pred])
                            print(fingerprint_retries)
                            if len(fingerprint_retries) == 3:
                                if len(set(fingerprint_retries)) == 1:
                                    malacious_sendmail()
                                fingerprint_retries = []
                            print('Fingerprint isn\'t matched')
                            print('Access Denied!!!')
                            buzzer_alert()
                        if pred != -1:
                            cv2.waitKey(1)
                            cv2.destroyAllWindows()
                            for i in range(0, 5):
                                cv2.waitKey(1)
                        for i in range(0, 100):
                            frame = video.get_frame()
                            frame = cv2.flip(frame, -1)
                        continue

                    elif detection_mode == 'attendance':
                        name_attended = labels_people[pred]
                        is_attended = 0
                        print('Detected ' + name_attended)
                        now = datetime.now()
                        now_string = now.strftime("%d/%m/%Y %H:%M:%S")
                        with open('attendance_data.csv',
                                  mode='r') as attendance_data:
                            attendances = csv.reader(attendance_data)
                            for row in attendances:
                                if row[2] == name_attended:
                                    is_attended = 1
                        if is_attended == 1:
                            print(name_attended + ' is already attended')
                        elif is_attended == 0:
                            with open('attendance_data.csv',
                                      mode='a') as attendance_data:
                                attendance_writer = csv.writer(
                                    attendance_data,
                                    delimiter=',',
                                    quotechar='"',
                                    quoting=csv.QUOTE_MINIMAL)
                                attendance_writer.writerow([
                                    str(counter),
                                    str(pred),
                                    str(labels_people[pred]),
                                    str(now_string)
                                ])
                        counter += 1

                else:
                    cv2.putText(frame, "Unknown",
                                (faces_coord[i][0], faces_coord[i][1]),
                                cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255),
                                1, cv2.LINE_AA)

        cv2.putText(frame, "ESC to exit", (5, frame.shape[0] - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1,
                    cv2.LINE_AA)
        cv2.imshow('Live Video Transmission', frame)
        if cv2.waitKey(100) & 0xFF == 27:
            sys.exit()
예제 #8
0
def recognize_people(people_folder, shape):

    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print("Have you added at least one person to the system?")
        sys.exit()
    print("This are the people in the Recognition System:")
    for person in people:
        print("-" + person)
    print("   POSSIBLE RECOGNIZERS TO USE")
    print("1. EigenFaces")
    print("2. FisherFaces")
    print("3. LBPHFaces")

    choice = check_choice()

    detector = FaceDetector('face_recognition_system/frontal_face.xml')
    if choice == 1:
        recognizer = cv2.face.EigenFaceRecognizer_create()
        threshold = 4000
    elif choice == 2:
        recognizer = cv2.face.FisherFaceRecognizer_create()
        threshold = 300
    elif choice == 3:
        recognizer = cv2.face.LBPHFaceRecognizer_create()
        threshold = 105
        #recognizer=VotingClassifier([('eigen',recognizer1),('lbph',recognizer2),('fisher',recognizer3)],voting='soft')

    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + '/' + image, 0))
            labels.append(i)
    try:
        #print("printing images"+"   "+"  "+str(images))
        #print("printing labesl"+"   "+"  "+str(labels)+"   "+str(np.array(labels)))
        recognizer.train(images, np.array(labels))
    except:
        print(
            "\nOpenCV Error: Do you have at least two people in the database?\n"
        )
        sys.exit()

    video = VideoCamera()
    while True:
        frame = video.get_frame()
        faces_coord = detector.detect(frame, False)
        if len(faces_coord):
            frame, faces_img = get_images(frame, faces_coord, shape)
            for i, face_img in enumerate(faces_img):
                #if __version__ == "3.1.0":
                global students
                collector = cv2.face.StandardCollector_create()
                #recognizer.predict(face_img)
                #conf = collector.getDist()
                #pred = collector.getLabel()
                #print ("Prediction: " +pred)
                #else:
                pred, conf = recognizer.predict(face_img)
                print("Prediction: " + str(pred))
                students.add(pred)
                print(students)
                print('Confidence: ' + str(round(conf)))
                print('Threshold: ' + str(threshold))
                if conf < threshold:
                    cv2.putText(frame, labels_people[pred].capitalize(),
                                (faces_coord[i][0], faces_coord[i][1] - 2),
                                cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                cv2.LINE_AA)
                else:
                    cv2.putText(frame, "Unknown",
                                (faces_coord[i][0], faces_coord[i][1]),
                                cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                cv2.LINE_AA)

        cv2.putText(frame, "ESC to exit", (5, frame.shape[0] - 5),
                    cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2, cv2.LINE_AA)
        cv2.imshow('Video', frame)
        if cv2.waitKey(100) & 0xFF == 27:

            dao = DAO(students)
            dao.dbOperations()
            print(
                "*******************************Attendence Updated ****************************"
            )
            #dao.__del__()
            sys.exit()
예제 #9
0
def recognize_people(people_folder, shape):
    """ Start recognizing people in a live stream with your webcam

    :param people_folder: relative path to save the person's pictures in
    :param shape: Shape to cut the faces on the captured images:
                  "rectangle" or "ellipse"
    :type people_folder: String
    :type shape: String
    """
    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print "Have you added at least one person to the system?"
        sys.exit()
    print "This are the people in the Recognition System:"
    for person in people:
        print "-" + person

    print 30 * "-"
    print "   POSSIBLE RECOGNIZERS TO USE"
    print 30 * "-"
    print "1. EigenFaces"
    print "2. FisherFaces"
    print "3. LBPHFaces"
    print 30 * "-"

    choice = check_choice()

    detector = FaceDetector("face_recognition_system/frontal_face.xml")
    if choice == 1:
        recognizer = cv2.face.createEigenFaceRecognizer()
        threshold = 4000
    elif choice == 2:
        recognizer = cv2.face.createFisherFaceRecognizer()
        threshold = 300
    elif choice == 3:
        recognizer = cv2.face.createLBPHFaceRecognizer()
        threshold = 105
    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + "/" + image, 0))
            labels.append(i)
    try:
        recognizer.train(images, np.array(labels))
    except:
        print "\nOpenCV Error: Do you have at least two people in the database?\n"
        sys.exit()

    video = VideoCamera()
    while True:
        frame = video.get_frame()
        faces_coord = detector.detect(frame, False)
        if len(faces_coord):
            frame, faces_img = get_images(frame, faces_coord, shape)
            for i, face_img in enumerate(faces_img):
                if __version__ == "3.1.0":
                    collector = cv2.face.MinDistancePredictCollector()
                    recognizer.predict(face_img, collector)
                    conf = collector.getDist()
                    pred = collector.getLabel()
                else:
                    pred, conf = recognizer.predict(face_img)
                print "Prediction: " + str(pred)
                print "Confidence: " + str(round(conf))
                print "Threshold: " + str(threshold)
                if conf < threshold:
                    cv2.putText(
                        frame,
                        labels_people[pred].capitalize(),
                        (faces_coord[i][0], faces_coord[i][1] - 2),
                        cv2.FONT_HERSHEY_PLAIN,
                        1.7,
                        (206, 0, 209),
                        2,
                        cv2.LINE_AA,
                    )
                else:
                    cv2.putText(
                        frame,
                        "Unknown",
                        (faces_coord[i][0], faces_coord[i][1]),
                        cv2.FONT_HERSHEY_PLAIN,
                        1.7,
                        (206, 0, 209),
                        2,
                        cv2.LINE_AA,
                    )

        cv2.putText(
            frame, "ESC to exit", (5, frame.shape[0] - 5), cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2, cv2.LINE_AA
        )
        cv2.imshow("Video", frame)
        if cv2.waitKey(100) & 0xFF == 27:
            sys.exit()
예제 #10
0
def recognize_people(people_folder, shape):
    # type: (object, object) -> object
    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print "Have you added at least one person to the system?"
        #sys.exit()
    '''print "These are the people in the Recognition System:"
    for person in people:
        print "-" + person

    print 30 * '-'
    print "   POSSIBLE RECOGNIZERS TO USE"
    print 30 * '-'
    print "1. EigenFaces"
    print "2. FisherFaces"
    print "3. LBPHFaces"
    print 30 * '-'
    '''
    choice = 3

    detector = FaceDetector('haarcascade_frontalface_default.xml')
    if choice == 1:
        recognizer = cv2.createEigenFaceRecognizer()
        threshold = 3500
    elif choice == 2:
        recognizer = cv2.createFisherFaceRecognizer()
        threshold = 300
    elif choice == 3:
        recognizer = cv2.createLBPHFaceRecognizer()
        threshold = 100
    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + '/' + image, 0))
            labels.append(i)
    try:
        recognizer.train(images, np.array(labels))
    except:
        print "\nOpenCV Error: Do you have at least two people in the database?\n"
        #sys.exit()

    video = VideoCamera()

    while True:
            frame = video.get_frame()
            faces_coord = detector.detect(frame, False)
            if len(faces_coord):
                frame, faces_img = get_images(frame, faces_coord, shape)
                for i, face_img in enumerate(faces_img):
                    if __version__ == "3.1.0":
                        collector = cv2.MinDistancePredictCollector()
                        recognizer.predict(face_img, collector)
                        conf = collector.getDist()
                        pred = collector.getLabel()
                    else:
                        pred, conf = recognizer.predict(face_img)

                    print "Prediction: " + str(pred)
                    print 'Confidence: ' + str(round(conf))
                    print 'Threshold: ' + str(threshold)

                    if conf < threshold:
                        cv2.putText(frame, labels_people[pred].capitalize(),
                                    (faces_coord[i][0], faces_coord[i][1] - 2),
                                    cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                    cv2.CV_AA)
                        c.writerow(people[pred].split())
                    else:
                        cv2.putText(frame, "Unknown",
                                    (faces_coord[i][0], faces_coord[i][1] - 2),
                                    cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                    cv2.CV_AA)

            cv2.putText(frame, "ESC to exit", (5, frame.shape[0] - 5),
                        cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2, cv2.CV_AA)
            cv2.imshow('Video', frame)
            if cv2.waitKey(100) & 0xFF == 27:
                exit()
def recognize_people(people_folder, shape):
    """ Start recognizing people in a live stream with your webcam
    """
    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print ("Have you added at least one person to the system?")
        sys.exit()
    print ("This are the people in the Recognition System:")
    for person in people:
        print ("-" + person)

    print (30 * '-')
    print ("   POSSIBLE RECOGNIZERS TO USE")
    print (30 * '-')
    print ("1. EigenFaces")
    print ("2. FisherFaces")
    print ("3. LBPHFaces")
    print (30 * '-')

    choice = check_choice()

    detector = FaceDetector('face_recognition_system/frontal_face.xml')
    if choice == 1:
        recognizer = cv2.face.createEigenFaceRecognizer()
        threshold = 4000
    elif choice == 2:
        recognizer = cv2.face.createFisherFaceRecognizer()
        threshold = 300
    elif choice == 3:
        recognizer = cv2.face.createLBPHFaceRecognizer()
        threshold = 80
    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + '/' + image, 0))
            labels.append(i)
    try:
        recognizer.train(images, np.array(labels))
    except:
        print ("\nOpenCV Error: Do you have at least two people in the database?\n")
        sys.exit()

    video = VideoCamera()
    while True:
        
        frame = video.get_frame()
        faces_coord = detector.detect(frame, False)
        if len(faces_coord):
            frame, faces_img = get_images(frame, faces_coord, shape)
            for i, face_img in enumerate(faces_img):
                if __version__ == "3.1.0":
                    collector = cv2.face.MinDistancePredictCollector()
                    recognizer.predict(face_img, collector)
                    conf = collector.getDist()
                    pred = collector.getLabel()
                else:
                    pred, conf = recognizer.predict(face_img)
                print ("Prediction: " + str(pred))
                print ('Confidence: ' + str(round(conf)))
                print ('Threshold: ' + str(threshold))
                if conf < threshold:
                    cv2.putText(frame, labels_people[pred].capitalize(),
                                (faces_coord[i][0], faces_coord[i][1] - 2),
                                cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1,
                                cv2.LINE_AA)
                else:
                    cv2.putText(frame, "Unknown",
                                (faces_coord[i][0], faces_coord[i][1]),
                                cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1,
                                cv2.LINE_AA)

        cv2.putText(frame, "ESC to exit", (5, frame.shape[0] - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255, 255), 1, cv2.LINE_AA)
        cv2.imshow('Video', frame)
        if cv2.waitKey(100) & 0xFF == 27:
            sys.exit()
def recognize_people(people_folder, shape):
    """ Start recognizing people in a live stream with your webcam

    :param people_folder: relative path to save the person's pictures in
    :param shape: Shape to cut the faces on the captured images:
                  "rectangle" or "ellipse"
    :type people_folder: String
    :type shape: String
    """
    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print "Have you added at least one person to the system?"
        sys.exit()
    print "These are the people in the Recognition System:"
    for person in people:
        print "-" + person

    #print 30 * '-'
    #print "   POSSIBLE RECOGNIZERS TO USE"
    #print 30 * '-'
    #print "1. EigenFaces"
    #print "2. FisherFaces"
    #print "3. LBPHFaces"
    #print 30 * '-'
    #
    #choice = check_choice()

    detector = FaceDetector('face_recognition_system/frontal_face.xml')
    #if choice == 1:
    #    recognizer = cv2.face.createEigenFaceRecognizer()
    #    threshold = 4000
    #elif choice == 2:
    #    recognizer = cv2.face.createFisherFaceRecognizer()
    #    threshold = 300
    #elif choice == 3:
    #    recognizer = cv2.face.createLBPHFaceRecognizer()
    #    threshold = 105
    recognizer = cv2. face. createLBPHFaceRecognizer()
    threshold = 100
    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + '/' + image, 0))
            labels.append(i)
    #print labels_people
    try:
        recognizer.train(images, np.array(labels))
    except:
        print "\nOpenCV Error: Do you have at least two people in the database?\n"
        sys.exit()


    file_ = "/var/www/html/facerecognitionapp/f.txt"

    engine = pyttsx.init()
    engine.setProperty('rate',200)
    #video = VideoCamera()
    fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows = True)
    stream=urllib.urlopen('http://192.168.206.175//mjpg/video.mjpg')
    bytes=''
    while(True):
        bytes+=stream.read(1024)
        bytes+=stream.read(1024)
        a = bytes.find('\xff\xd8')
        b = bytes.find('\xff\xd9')
        if a!=-1 and b!=-1:
            jpg = bytes[a:b+2]
            bytes= bytes[b+2:]
            frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)
            fgmask = fgbg.apply(frame)
    #while True:
    #    frame = video.get_frame()
            faces_coord = detector.detect(frame, False)
            if len(faces_coord):
                frame, faces_img = get_images(frame, faces_coord, shape)
                for i, face_img in enumerate(faces_img):
                    if __version__ == "3.1.0":
                        collector = cv2.face.MinDistancePredictCollector()
                        recognizer.predict(face_img, collector)
                        conf = collector.getDist()
                        pred = collector.getLabel()
                    else:
                        pred, conf = recognizer.predict(face_img)
                    print "Prediction: " + str(pred)
                    print 'Confidence: ' + str(round(conf))
                    print 'Threshold: ' + str(threshold)
                    print labels_people[int(pred)]
                    if conf < threshold:
                        cv2.putText(frame, labels_people[pred].capitalize(),
                                    (faces_coord[i][0], faces_coord[i][1] - 2),
                                    cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                    cv2.LINE_AA)#
                        with open (file_,"a+") as f:
                            for Line in f:
                                Line = Line.split(";")
                                for i in range(0,len(Line)/2):
                                    if Line [i*2] == labels_people[int(pred)]:                                     #Line[i*2+1]=int(time.time())
                                        break
                                else:
                                    f.write(";{};{}".format(labels_people[int(pred)],time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())))
                                    command = "Welcome " + labels_people[int(pred)]+" to Winlab";
                                    print command
                                    engine.say(command)
                                    engine.runAndWait()
                                    time.sleep(1)
                    else:
                        cv2.putText(frame, "Unknown",
                                    (faces_coord[i][0], faces_coord[i][1]),
                                    cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                    cv2.LINE_AA)#
            cv2.putText(frame, "ESC to exit", (5, frame.shape[0] - 5),
                        cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2, cv2.LINE_AA)
            line1 = np.array([[666,0],[666,750]],np.int32).reshape((-1,1,2))
            frame = cv2.polylines(frame,[line1],False,(0,255,0),thickness=3)
            cv2.imshow('Video test....', frame)
            line2 = np.array([[666,0],[666,300]],np.int32).reshape((-1,1,2))
            fgmask = cv2.polylines(fgmask,[line2],False,(0,255,255),thickness=3)
            cv2.imshow('Background',fgmask)
            if cv2.waitKey(100) & 0xFF == 27:
                sys.exit()
예제 #13
0
def recognize_people(people_folder, shape):
    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print "Have you added at least one person to the system?"
        sys.exit()
    '''    
    print "This are the people in the Recognition System:"
    for person in people:
        print "-" + person
    '''

    detector = FaceDetector('face_recognition_system/frontal_face.xml')

    recognizer = cv2.createLBPHFaceRecognizer()
    threshold = 105

    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + '/' + image, 0))
            labels.append(i)
    try:
        recognizer.train(images, np.array(labels))
    except:
        print "\nOpenCV Error: Do you have at least two people in the database?\n"
        sys.exit()

    video = VideoCamera()

    person_id = raw_input('Enter Your ID:')
    boolean = "true"
    while boolean == "true":
        frame = video.get_frame()
        faces_coord = detector.detect(frame, False)
        if len(faces_coord):
            frame, faces_img = get_images(frame, faces_coord, shape)
            for i, face_img in enumerate(faces_img):
                if __version__ == "3.1.0":
                    collector = cv2.face.MinDistancePredictCollector()
                    recognizer.predict(face_img, collector)
                    conf = collector.getDist()
                    pred = collector.getLabel()
                else:
                    pred, conf = recognizer.predict(face_img)
            #print "Prediction: " + str(pred)
            #print 'Confidence: ' + str(round(conf))
            #print 'Threshold: ' + str(threshold)

                if conf < threshold:
                    cv2.putText(frame, labels_people[pred].capitalize(),
                                (faces_coord[i][0], faces_coord[i][1] - 2),
                                cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                cv2.CV_AA)

                else:
                    cv2.putText(frame, "Unknown",
                                (faces_coord[i][0], faces_coord[i][1]),
                                cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                cv2.CV_AA)

                cv2.imshow('Video', frame)
                if (labels_people[pred] == str(person_id)
                        and boolean == "true"):
                    conn = pyodbc.connect(
                        "DRIVER={SQL Server};Server=DESKTOP-M4SA4AV;Database=Ds;uid=DESKTOP-M4SA4AV\fadel;pwd=;Trusted_Connection=yes;"
                    )
                    cursor = conn.cursor()
                    cursor.execute("SELECT * FROM grades where username='******'")
                    results = cursor.fetchone()
                    print("Welcome " + str(labels_people[pred]))
                    while results:
                        print("course:" + str(results[1]) + " grade:" +
                              str(results[2]))

                        results = cursor.fetchone()

            #cv2.putText(frame, "ESC to exit", (5, frame.shape[0] - 5),cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2, cv2.CV_AA)
        if cv2.waitKey(100) & 0xFF == 27:
            sys.exit()
예제 #14
0
def recognize_people_from_external_video(people_folder, shape):
    """ Start recognizing people in a live stream with your webcam

    :param people_folder: relative path to save the person's pictures in
    :param shape: Shape to cut the faces on the captured images:
                  "rectangle" or "ellipse"
    :type people_folder: String
    :type shape: String
    """
    try:
        people = [person for person in os.listdir(people_folder)]
    except:
        print ("Have you added at least one person to the system?")
        sys.exit()
    print ("This are the people in the Recognition System:")
    for person in people:
        print ("-" + person)

    print (30 * '-')
    print ("   POSSIBLE RECOGNIZERS TO USE")
    print (30 * '-')
    print ("1. EigenFaces")
    print ("2. FisherFaces")
    print ("3. LBPHFaces")
    print (30 * '-')

    choice = check_choice()

    detector = FaceDetector('face_recognition_system/frontal_face.xml')
    if choice == 1:
        recognizer = cv2.face.EigenFaceRecognizer_create()
        threshold = 4000
    elif choice == 2:
        recognizer = cv2.face.FisherFaceRecognizer_create()
        threshold = 300
    elif choice == 3:
        recognizer = cv2.face.LBPHFaceRecognizer_create()
        threshold = 85
    images = []
    labels = []
    labels_people = {}
    for i, person in enumerate(people):
        labels_people[i] = person
        for image in os.listdir(people_folder + person):
            images.append(cv2.imread(people_folder + person + '/' + image, 0))
            labels.append(i)
    try:
        recognizer.train(images, np.array(labels))
    except:
        print ("\nOpenCV Error: Do you have at least two people in the database?\n")
        sys.exit()

    video = ExternalVideo()
    # Define the codec and create VideoWriter object
    #fourcc = cv2.VideoWriter_fourcc(*'H264')
    #myvideo = cv2.VideoWriter('video/video_rod_garage2.avi',-1, 10.0, (640,480))
    # Get the width and height of frame
    
    # Define the codec and create VideoWriter object

    counter = 0;
    while True:
        frame = video.get_frame()
        if counter == 0:
            print("Exceuted if")
            [h, w] = frame.shape[:2]
            out = cv2.VideoWriter("video/garage_out.avi", 0, 25.0, (w, h))
        counter = 1
        faces_coord = detector.detect(frame, False)
        if len(faces_coord):
            frame, faces_img = get_images(frame, faces_coord, shape)
            print("Version",__version__)
            for i, face_img in enumerate(faces_img):
#                if __version__ == "3.1.0":
#                    collector = cv2.face.MinDistancePredictCollector()
#                    recognizer.predict(face_img, collector)
#                    conf = collector.getDist()
#                    pred = collector.getLabel()
#                else:
#                    pred, conf = recognizer.predict(face_img)
                pred, conf = recognizer.predict(face_img)
                print ("Prediction: " + str(pred))
                print ('Confidence: ' + str(round(conf)))
                print ('Threshold: ' + str(threshold))
                if conf < threshold:
                    cv2.putText(frame, labels_people[pred].capitalize(),
                                (faces_coord[i][0], faces_coord[i][1] -2 ),
                                cv2.FONT_HERSHEY_PLAIN, 2.5, (206, 0, 209), 2,
                                cv2.LINE_AA)
                else:
                    cv2.putText(frame, "Unknown",
                                (faces_coord[i][0] , faces_coord[i][1]),
                                cv2.FONT_HERSHEY_PLAIN, 2.5, (206, 0, 209), 2,
                                cv2.LINE_AA)

        cv2.putText(frame, "ESC to exit", (5, frame.shape[0] - 5),
                    cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2, cv2.LINE_AA)

        out.write(frame)
        cv2.imshow('Video', frame)
        if cv2.waitKey(1) & 0xFF == 27:
            out.release()
            sys.exit()