Exemplo n.º 1
0
def add_person(people_folder, shape):
    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)
                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', cv2.flip(frame, 1))
            cv2.waitKey(2)
            timer += 5
    else:
        print "This name already exists."
        sys.exit()
Exemplo n.º 2
0
def func_addperson(people_folder, shape, folder):
    count = 0
    while (count < 5):
        raw_input("I will now take 20 pictures. Press ENTER when ready.")
        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:
                    now = datetime.datetime.now()
                    stringnow = str("%d" % now.year + "%d" % now.month +
                                    "%d" % now.day + "%d" % now.hour +
                                    "%d" % now.minute + "%d" % now.second)
                    cv2.imwrite(folder + '/' + str(stringnow) + '.jpg',
                                face_img[0])
                    print("Images Saved: " + str(stringnow))
                    cv2.imshow('Saved Face', face_img[0])
                    counter += 1
            cv2.putText(frame, str(timer % 100), (5, frame.shape[0] - 5),
                        cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2,
                        cv2.LINE_AA)
            cv2.imshow('Video Feed', frame)
            cv2.waitKey(50)
            timer += 5
        count += 1
Exemplo n.º 3
0
def add_person(people_folder, shape):
    person_name = input('Name of the new person: ').lower()
    folder = people_folder + person_name
    if os.path.exists(folder):
        shutil.rmtree(folder)
    input("Press ENTER to start taking pictures")
    os.mkdir(folder)
    video = VideoCamera()
    detector = FaceDetector('face_recognition_system/haarcascade_frontalface_alt2.xml')
    counter = 1
    timer = 0
    while counter < 51:
        frame = video.get_frame()
        face_coord = detector.detect(frame)
        if len(face_coord):
            frame, face_img = get_images(frame, face_coord, shape)
            if timer % 10 == 5:
                cv2.imwrite(folder + '/' + str(counter) + '.jpg',
                            face_img[0])
                counter += 1

        cv2.imshow('Video Feed', frame)
        cv2.waitKey(50)
        timer += 5
    cv2.destroyAllWindows()
Exemplo n.º 4
0
def add_person(people_folder, shape):

    person_name = input('Please give the name of the new person: ').lower()
    folder = people_folder + person_name
    if not os.path.exists(folder):
        input("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()
Exemplo n.º 5
0
def add_person(people_folder, shape, person):
    #Directly taking argument instead of command line
    folder = people_folder + person
    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()
Exemplo n.º 6
0
def recognize_people(people_folder, shape):
    people = [person for person in os.listdir(people_folder)]

    print (30 * '-')
    detector = FaceDetector('face_recognition_system/haarcascade_frontalface_alt2.xml')
    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)
                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:
            cv2.destroyAllWindows()
            sys.exit()
Exemplo n.º 7
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)
        mood_adj = "How do you look like?"
        while counter < 21:
            frame = video.get_frame()
            face_coord = detector.detect(frame)
            if len(face_coord):
                cv2.putText(frame, mood_adj.capitalize(),
                            (face_coord[0][0], face_coord[0][1]),
                            cv2.FONT_HERSHEY_PLAIN, 1.7, (0, 3, 209), 2,
                            cv2.LINE_AA)

                frame, face_img = get_images(frame, face_coord, shape)
                # save a face every second (100), we start from an offset '5' because
                # the first frame of the camera gets very high intensity
                # readings.
                if timer % 100 == 5:

                    (conf_adj, mood_adj) = analyze_face(frame)
                    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()
def add_person(people_folder, shape, netcam):
    """ 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("Ready to take 20 pictures. Press ENTER when ready.")
        os.mkdir(folder)

    video = VideoCamera(netcam)
    detector = FaceDetector('face_recognition_system/frontal_face.xml')
    counter = 1
    timer = 0
    cv2.namedWindow('Video Feed', cv2.WINDOW_NORMAL)
    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 % 70 == 5:  # 1 Second is = 100, less than a sec is < 100
                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)
        timer += 5
        k = cv2.waitKey(50) & 0xff
        if k == 27:
            break

    del video
    cv2.destroyAllWindows()
Exemplo n.º 9
0
def add_person(people_folder, shape, user_name):
    """ Funtion to add pictures of a person
    """
    folder = people_folder + str(user_name)
    if not os.path.exists(folder):
        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 < 5:
            # I changed it to 11 to get 10 pics, it was 5
            frame = video.get_frame()
            frame = cv2.flip(frame, -1)
            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])
                    if counter == 5:
                        # I changed it to 11 to get 10 pics, it was 5
                        cv2.waitKey(1)
                        cv2.destroyAllWindows()
                        for i in range(0, 5):
                            cv2.waitKey(1)
                        break

            cv2.imshow('Video Feed', frame)
            cv2.waitKey(50)
            timer += 5
    else:
        print("This name already exists.")
        sys.exit()
Exemplo n.º 10
0
def add_person(people_folder):
    """ 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 full 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)
                # 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()
Exemplo n.º 11
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()
Exemplo n.º 12
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()
Exemplo n.º 13
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()
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()
Exemplo n.º 15
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()
Exemplo n.º 16
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()
Exemplo n.º 17
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()
Exemplo n.º 19
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()