def __init__(self, profile_activated):
        self.profile_activated = profile_activated
        self.model_path = BASE_DIR + SPERATOR + "facedatabase" + SPERATOR
        self.svm_model_name = "trained_classifier.pkl"
        self.image_rep_name = "faces.npy"
        self.people_rep_name = "people.npy"
        self.image_folder_path = "images" + SPERATOR
        if self.profile_activated is True:
            print("FaceRecognition: initialize face recognizer")
        self.svm = None
        self.training = False
        self.training_id = 0
        self.training_name = "Unknown"
        self.trainingInProgress = False
        self.identify_threshold = 0.8
        self.face_classfier = None

        if not os.path.exists(self.model_path):
            os.makedirs(self.model_path)

        if self.profile_activated is True:
            print("FaceRecognition: loading prepresentations of kownen persons")
        try:
            self.images = np.load(self.model_path + SPERATOR + self.image_rep_name,allow_pickle=True).item()
        except IOError:
            if self.profile_activated is True:
                print("Warning: no image representation file found")
            self.images = {}
        try:
            self.people = np.load(self.model_path + SPERATOR + self.people_rep_name,allow_pickle=True).item()
        except IOError:
            if self.profile_activated is True:
                print("Warning: no people representation file found")
            self.people = {}
            self.people["0"] = "Unknown"

        if self.profile_activated is True:
            print ("FaceRecognition: try to load saved svm for estimation")
        try:
            self.face_classfier = FaceClassifier(self.model_path + SPERATOR + self.svm_model_name)
        except IOError:
            if self.profile_activated is True:
                print ("Warning: no svm saved")
            self.face_classfier = None
        if self.profile_activated is True:
            print ("FaceRecognition: initialisation done")

        self.tracker_sort = Sort(25,3)
    def trainSVM(self):
        self.trainingInProgress = True
        if self.profile_activated is True:
            print ("FaceRecognition: Training SVM on {} labeled images.".format(len(self.images)))
        d = self.getData()
        if d is None:
            self.face_classfier = None
            if self.profile_activated is True:
                print ("FaceRecognition: at least 2 persons needed ..")
                self.trainingInProgress = False
            return
        else:
            (X, y) = d
            numIdentities = len(set(y + [-1]))
            if numIdentities <= 1:
                self.trainingInProgress = False
                return

            self.face_classfier = FaceClassifier()
            self.face_classfier.train(X, y, model='svm', save_model_path=(self.model_path + SPERATOR + self.svm_model_name))
            self.saveImageDataAndTrainedNet()
            print ("training done!")
            self.trainingInProgress = False
Пример #3
0
import cv2
import time
import numpy as np
from detection.FaceDetector import FaceDetector
from recognition.FaceRecognition import FaceRecognition
from classifier.FaceClassifier import FaceClassifier

face_detector = FaceDetector()
face_recognition = FaceRecognition()
face_classfier = FaceClassifier('./classifier/trained_classifier.pkl')
video_capture = cv2.VideoCapture(0)

print('Start Recognition!')
prevTime = 0
while True:
    ret, frame = video_capture.read()
    frame = cv2.resize(frame, (0, 0), fx=1, fy=1)  # resize frame (optional)
    #time.sleep(1)
    curTime = time.time()  # calc fps
    find_results = []

    frame = frame[:, :, 0:3]
    boxes, scores = face_detector.detect(frame)
    face_boxes = boxes[np.argwhere(scores>0.3).reshape(-1)]
    face_scores = scores[np.argwhere(scores>0.3).reshape(-1)]
    print('Detected_FaceNum: %d' % len(face_boxes))

    if len(face_boxes) > 0:
        for i in range(len(face_boxes)):
            box = face_boxes[i]
            cropped_face = frame[box[0]:box[2], box[1]:box[3], :]
Пример #4
0
    return names[ind]
def _update_attendance(attendance_list):
    '''
    Updates attendance

    Args:
    attend

    '''
    with open(args.attendance_file,"w") as f:
        attendance_list=[a+"\n" for a in attendance_list]
        f.writelines(attendance_list)

face_detector = FaceDetector(PATH_TO_CKPT=detect_ckpt)
face_recognition = FaceRecognition(PATH_TO_CKPT=recog_ckpt)
face_classfier = FaceClassifier(args.trained_classifier)
face_classfier_svm=FaceClassifier('./classifier/trained_svm.pkl')
face_classfier_knn7=FaceClassifier('./classifier/knn_7.pkl')
face_classfier_knn7=FaceClassifier('./classifier/knn_5.pkl')
face_classfier_rf=FaceClassifier('./classifier/random_forests.pkl')

#video_capture = cv2.VideoCapture(args.camera)
video_capture = cv2.VideoCapture(0)
print('Start Recognition!')
prevTime = 0
count=0
attendance_list=[]
skip=0
while True:
    
    ret, frame = video_capture.read()
    "all"
]

input_folder = path.join(path.abspath(path.curdir), "data", "input")

people_folders = None
number_imgs_list = []
embeddings = []
embeddings_ids = []

embeddings_df = None
people_df = None

vector_size = None

face_classifier = FaceClassifier()


def download(file_path, url):
    import requests
    import math

    r = requests.get(url, stream=True)
    total_size = int(r.headers.get('content-length'))
    block_size = 1024

    with open(file_path, 'wb') as f:
        for data in tqdm(r.iter_content(block_size), total=math.ceil(total_size // block_size), desc="Download",
                         unit='B', unit_scale=True, unit_divisor=1024):
            f.write(data)
Пример #6
0
import cv2
import time
import numpy as np
from detection.FaceDetector import FaceDetector
from recognition.FaceRecognition import FaceRecognition
from classifier.FaceClassifier import FaceClassifier

VIDEO_INPUT_FILE = './media/test_video/Zidane_1.avi'
VIDEO_OUTPUT_FILE = './media/test_video_output/Zidane_Recognition_1.avi'
FACE_CLASSIFIER_MODEL = './classifier/trained_classifier_lfw.pkl'

face_detector = FaceDetector()
face_recognition = FaceRecognition()
face_classfier = FaceClassifier(FACE_CLASSIFIER_MODEL)
video_capture = cv2.VideoCapture(VIDEO_INPUT_FILE)

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(VIDEO_OUTPUT_FILE, fourcc, 24.0,
                      (int(video_capture.get(3)), int(video_capture.get(4))))

print('Start Recognition!')
prevTime = 0
while video_capture.isOpened():
    ret, frame = video_capture.read()

    curTime = time.time()  # calc fps
    find_results = []

    frame = frame[:, :, 0:3]
    boxes, scores = face_detector.detect(frame)
    face_boxes = boxes[np.argwhere(scores > 0.3).reshape(-1)]
Пример #7
0
def main(args):
    face_detector = FaceDetector()
    face_recognition = FaceRecognition(args.model)
    face_classfier = FaceClassifier(args.classifier_filename)
    video_capture = cv2.VideoCapture(args.video_input)
    output_file = './media/result/' + os.path.basename(
        args.video_input) + '_result.avi'

    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter(
        output_file, fourcc, 24.0,
        (int(video_capture.get(3)), int(video_capture.get(4))))

    print('Start Recognition!')
    prevTime = 0
    while video_capture.isOpened():
        ret, frame = video_capture.read()

        curTime = time.time()  # calc fps
        find_results = []

        frame = frame[:, :, 0:3]
        boxes, scores = face_detector.detect(frame)
        face_boxes = boxes[np.argwhere(scores > 0.3).reshape(-1)]
        face_scores = scores[np.argwhere(scores > 0.3).reshape(-1)]
        print('Detected_FaceNum: %d' % len(face_boxes))

        if len(face_boxes) > 0:
            for i in range(len(face_boxes)):
                box = face_boxes[i]
                cropped_face = frame[box[0]:box[2], box[1]:box[3], :]
                cropped_face = cv2.resize(cropped_face, (160, 160),
                                          interpolation=cv2.INTER_AREA)
                feature = face_recognition.recognize(cropped_face)
                name = face_classfier.classify(feature)

                cv2.rectangle(frame, (box[1], box[0]), (box[3], box[2]),
                              (0, 255, 0), 2)

                # plot result idx under box
                text_x = box[1]
                text_y = box[2] + 20
                cv2.putText(frame,
                            name, (text_x, text_y),
                            cv2.FONT_HERSHEY_COMPLEX_SMALL,
                            1, (0, 0, 255),
                            thickness=1,
                            lineType=2)
        else:
            print('Unable to align')

        sec = curTime - prevTime
        prevTime = curTime
        fps = 1 / (sec)
        str = 'FPS: %2.3f' % fps
        text_fps_x = len(frame[0]) - 150
        text_fps_y = 20
        cv2.putText(frame,
                    str, (text_fps_x, text_fps_y),
                    cv2.FONT_HERSHEY_COMPLEX_SMALL,
                    1, (0, 0, 0),
                    thickness=1,
                    lineType=2)

        out.write(frame)

    video_capture.release()
    out.release()
    cv2.destroyAllWindows()
Пример #8
0
def _update_attendance(attendance_list):
    '''
    Updates attendance

    Args:
    attend

    '''
    with open(args.attendance_file, "w") as f:
        attendance_list = [a + "\n" for a in attendance_list]
        f.writelines(attendance_list)


face_detector = FaceDetector(PATH_TO_CKPT=detect_ckpt)
face_recognition = FaceRecognition(PATH_TO_CKPT=recog_ckpt)
face_classfier = FaceClassifier(args.trained_classifier)
#video_capture = cv2.VideoCapture(args.camera)

print('Start Recognition!')
prevTime = 0
count = 0
attendance_list = []
i = 1
while True:
    j = 37 + i
    path = './media/train_classifier/milind/'
    frame = cv2.imread(path +
                       'WhatsApp Image 2018-11-01 at 9.23.%d PM.jpeg' % j)
    print('%dth recognition' % i)
    i += 1
Пример #9
0
import numpy as np
from classifier.FaceClassifier import FaceClassifier
#Training  classifiers after obtaining the feaure vectors from the recognition model
features = np.load('./npy files/features.npy')
labels = np.load('./npy files/labels.npy')
face_classifier = FaceClassifier('./classifier/trained_svm.pkl')
Svm = face_classifier.train(
    features,
    labels,
    model='SVM',
    save_model_path='./classifier/new_classifiers/trained_svm.pkl')
#KNN = face_classifier.train(features,labels,model='knn',save_model_path='./classifier/trained_classifier.pkl')
KNN_5 = face_classifier.train(
    features,
    labels,
    model='knn',
    knn_neighbours=5,
    save_model_path='./classifier/new_classifiers/knn_5.pkl')
KNN_7 = face_classifier.train(
    features,
    labels,
    model='knn',
    knn_neighbours=7,
    save_model_path='./classifier/new_classifiers/knn_7.pkl')
random_forests = face_classifier.train(
    features,
    labels,
    model='random-forests',
    save_model_path='./classifier/new_classifiers/random_forests.pkl')
Svm_poly = face_classifier.train(
    features,
Пример #10
0
import time

import cv2
import numpy as np

from classifier.FaceClassifier import FaceClassifier
from detection.FaceDetector import FaceDetector
from embeddings.FaceEmbeddings import FaceEmbeddings

model = input("Choose a model> ")
# model = "knn"

face_detector = FaceDetector()
face_recognition = FaceEmbeddings()
face_classifier = FaceClassifier(
    f'./classifier/{model.lower()}_classifier.pkl')

video_capture = cv2.VideoCapture(0)
prevTime = 0
cv2.namedWindow("Video", cv2.WINDOW_NORMAL)

print('Start Recognition!')
while True:

    ret, frame = video_capture.read()
    # if not ret:
    #     break

    frame = cv2.resize(frame, (0, 0), fx=1, fy=1)  # resize frame (optional)
    curTime = time.time()  # calc fps