コード例 #1
0
class Doorman:
  """Main Doorman App for the Raspberry Pi."""

  def __init__(self):
    """Begin the app."""

    web_dir = os.path.join(os.path.dirname(__file__), 'html')
    os.chdir(web_dir)
    print('CWD:', web_dir)

    self.totp = TOTP('supersecretkey32') # Key unique to each user.

    self.fr = FaceRecognition()
    self.fr.set_request_unlock(request_unlock)

    self.server = WebServer(port=8080, ws_port=8081)
    self.server.set_begin_registration(self.begin_registration)
    self.server.set_verify_code(self.verify_code)

    self.requestedUnlock = False

    print('Hello world!')

    self.fr.start_recognition()

  def request_unlock(self):
    """Send request to client to unlock the computer."""
    self.server.request_unlock()
    self.requestedUnlock = True
    time.sleep(30)
    if self.requestedUnlock:
      self.request_lock()
      self.requestedUnlock = False

  def request_lock(self):
    """Send request to client to lock the computer."""
    self.server.request_lock()

  def begin_registration(self):
    """Handler for web request to register new user."""

    print('Registration beginning!')
    # TODO: Replace this with the registration process.

  def verify_code(self, code):
    """
    Handler for web request to verify the given code.

    :param code: The code to verify from the user.
    :return: True if verified successfully, False if invalid.
    """

    is_valid = self.totp.verify_totp(code)

    self.requestedUnlock = False

    if not is_valid:
      request_lock()

    return is_valid
コード例 #2
0
 def __init__(self):
     start = time.time()
     FaceRecognition.__init__(self)
     VedioBase.__init__(self)
     # self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
     # self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
     # track 5 faces in the sametime
     self.trackers = [dlib.correlation_tracker() for _ in range(7)]
     self.track_names = []
     self.detectd_faces = []
     print('init', time.time() - start)
コード例 #3
0
class RunFaceID(object):
    def __init__(self):
        super(RunFaceID, self).__init__()
        self.face_detection = FaceDetection()
        self.face_recognition = FaceRecognition()

    def predict(self, array_embeddings, embeddings_source):
        return "unknown"

    def processing(self, images, embeddings_source):
        frame = copy.deepcopy(images)
        faces = self.face_detection.detect_faces(frame)
        if faces is None or len(faces) < 1:
            return None
        data = {}
        array_img = []
        labels = []
        for x, y, w, h in faces:
            if w > 0 and h > 0:
                img_crop = frame[y:y + h, x:x + w, :]
                array_img.append(img_crop)
                # labels.append("unknown")
        array_img = np.array(array_img)
        # data["labels"] = labels
        if count >= NUMBER_FRAME:
            array_embeddings = self.face_recognition.embedding_image(array_img)
            data["labels"] = self.predict_labels(array_embeddings,
                                                 embeddings_source)
        data["bounding_boxs"] = faces
        return data
コード例 #4
0
  def __init__(self):
    """Begin the app."""

    web_dir = os.path.join(os.path.dirname(__file__), 'html')
    os.chdir(web_dir)
    print('CWD:', web_dir)

    self.totp = TOTP('supersecretkey32') # Key unique to each user.

    self.fr = FaceRecognition()
    self.fr.set_request_unlock(request_unlock)

    self.server = WebServer(port=8080, ws_port=8081)
    self.server.set_begin_registration(self.begin_registration)
    self.server.set_verify_code(self.verify_code)

    self.requestedUnlock = False

    print('Hello world!')

    self.fr.start_recognition()
コード例 #5
0
ファイル: app.py プロジェクト: hienptit123/Web_Demo_Co_Ha
class RunFaceID(object):
    def __init__(self):
        super(RunFaceID, self).__init__()
        self.face_detection = FaceDetection()
        self.face_recognition = FaceRecognition()
        self.arr_embeddings = pickle.load(open("data_embeddings", "rb"))
        self.labels = pickle.load(open("labels", "rb"))

    def predict_labels(self, embeddings):
        dis_cs = cs(embeddings, self.arr_embeddings)
        index_list = np.argmax(dis_cs, axis=-1)
        label_pred = []
        for i, index in enumerate(index_list):
            if dis_cs[i][index] > 0.6:
                label_pred.append(self.labels[index])
            else:
                label_pred.append("unknown")
        return label_pred

    def processing(self, images, count):
        frame = copy.deepcopy(images)
        faces = self.face_detection.detect_faces(frame)
        if faces is None or len(faces) < 1:
            return None
        data = {}
        array_img = []
        labels = []
        for x, y, w, h in faces:
            if w > 0 and h > 0:
                img_crop = img_crop = frame[y:y + h, x:x + w, :]
                array_img.append(img_crop)
                labels.append("unknown")
        array_img = np.array(array_img)
        # data["labels"] = labels
        if count >= 5:
            array_embeddings = self.face_recognition.embedding_image(array_img)
            data["labels"] = self.predict_labels(array_embeddings)
        data["bounding_boxs"] = faces
        return data
コード例 #6
0
def train_dataframe(company_name):
    
    print("Loading Started...")
    known_faces = get_images_with_tag(company_name)
    all_ids = []
    all_locations = []
    fr = FaceRecognition()
    try:
        for name, known_file in known_faces:
           
            all_ids.append(name)
            all_locations.append(known_file)
            print("Loaded: " + name)
            
    except:
        print("Error for " + known_file + " tag: " + name)



    df = pd.DataFrame(list(zip(all_ids, all_locations)), columns =['person', 'path']) 
    print("Fitting started")
    fr.fit_from_dataframe(df)
    fr.save('/var/www/attendancekeeper_' + company_name + '/detector/knn.pkl')
    print("Fitting done")
コード例 #7
0
import argparse

#ap = argparse.ArgumentParser()
#ap.add_argument("-m", "--mode", required=True,
#	help="mode of face recognition, 'cam'-->webcam or 'vid'-->stored video")
#ap.add_argument("-d", "--directory", required=True,
#	help="path to root folder where person data is stored")
#ap.add_argument("-v", "--input", 
#	help="path to video input if mode is stored video")
#ap.add_argument("-o", "--output", required=True,
#	help="name of output video")
#ap.add_argument("-c", "--confidence", type=float, default=0.7,
#	help="confidence value for correct face recognition")
#args = vars(ap.parse_args())

FR = FaceRecognition()

def videoFR(path, personCount):
    count_frames = 0
    skip_frames = 3
    inputVideo = 'Friends.mp4' #args["input"]
    prob_th = 0.85 #args["confidence"]
    cap = cv2.VideoCapture(inputVideo)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))    
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    fps = cap.get(cv2.CAP_PROP_FPS)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    video = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    pbar = tqdm(total=total_frames, desc="[INFO] Processing video")
    while cap.isOpened():
コード例 #8
0
 def __init__(self):
     super(RunFaceID, self).__init__()
     self.face_detection = FaceDetection()
     self.face_recognition = FaceRecognition()
コード例 #9
0
ファイル: main (1).py プロジェクト: mindset-tt/face_detect
import os
from face_recognition import FaceRecognition

if __name__ == '__main__':
    model_name = "face_recognition.h5"
    image_path = 'test.jpg'
    face_recognition = FaceRecognition()
    face_recognition.training()
    face_recognition.save_model(model_name)
    model = FaceRecognition.load_saved_model(os.path.join("model", model_name))
    k = FaceRecognition.model_prediction(
        image_path, os.path.join("model", model_name),
        os.path.join("model", "face_recognition_class_names.npy"))
    print(f"detected class is {k}")
コード例 #10
0
ファイル: app.py プロジェクト: hungptit123/Web_Demo_Co_Ha
class RunFaceID(object):
    def __init__(self):
        super(RunFaceID, self).__init__()
        self.face_detection = FaceDetection()
        self.face_recognition = FaceRecognition()
        # self.arr_embeddings = pickle.load(open("data_embeddings", "rb"))
        # self.labels = pickle.load(open("labels", "rb"))

    def predict_labels(self, embeddings, embeddings_source, labels_index,
                       labels_name):
        dis_cs = cs(embeddings, embeddings_source)
        index_list = np.argmax(dis_cs, axis=-1)
        label_pred = []
        for i, index in enumerate(index_list):
            if dis_cs[i][index] > 0.6:
                label_index = labels_index[index]
                for i, (index_tmp, name_tmp) in enumerate(labels_name):
                    if label_index == index_tmp:
                        label_pred.append(labels_name[i])
            else:
                label_pred.append([-1, "unknown"])
        return label_pred

    def processing(self, images, count, embeddings_source, labels_index,
                   labels_name, message_status):
        frame = copy.deepcopy(images)
        faces = self.face_detection.detect_faces(frame)
        if faces is None or len(faces) < 1:
            return None
        data = {}
        array_img = []
        labels = []
        for x, y, w, h in faces:
            if w > 0 and h > 0:
                img_crop = frame[y:y + h, x:x + w, :]
                array_img.append(img_crop)
                # labels.append("unknown")
        array_img = np.array(array_img)
        # data["labels"] = labels
        if count >= NUMBER_FRAME:
            array_embeddings = self.face_recognition.embedding_image(array_img)
            data["labels"] = self.predict_labels(array_embeddings,
                                                 embeddings_source,
                                                 labels_index, labels_name)
        data["bounding_boxs"] = faces
        return data

    def get_faces(self, images):
        faces = self.face_detection.detect_faces(images)
        return list(faces)

    def get_bb_embeddings(self, images):
        faces = self.get_faces(images)
        if len(faces) != 1:
            return None
        array_img = []
        data = {}
        for x, y, w, h in faces:
            if w > 0 and h > 0:
                img_crop = images[y:y + h, x:x + w, :]
                array_img.append(img_crop)
        embeddings = self.face_recognition.embedding_image(array_img)[0]
        data["bounding_box"] = json.dumps(faces[0].tolist())
        data['embeddings'] = json.dumps(embeddings.tolist())
        return data
コード例 #11
0
def main():
    fr = FaceRecognition()
    rospy.spin()
コード例 #12
0
from face_recognition import FaceRecognition
import base64
from io import BytesIO

data = {
    'data':
    'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCACWASwDASIAAhEBAxEB/8QAGgAAAwEBAQEAAAAAAAAAAAAAAAECAwQFBv/EADMQAAICAgAEBAUDAwQDAAAAAAABAhEDIQQSMUETUWFxBSIygZEUobEjQtEzweHwUpLx/8QAGAEBAQEBAQAAAAAAAAAAAAAAAAECAwT/xAAcEQEBAQADAQEBAAAAAAAAAAAAARECITESQQP/2gAMAwEAAhEDEQA/APkUx2Rexow00vT2CZCY78iqvqFiTBBFX2sBXoYDBPYrCwG6GT6BYFB3EADHfYkLAfsACAq6AnqOwGHckdgOwJsdhTugEFlQwfUmwsiqvYWTYk+4F2K9k8wnIC2xNkcwXYFXsG/czbHzMgu7QnIi9ht9L+xdwRT7gaVRNX2oiE9ILDla2hFVXN6DUrI+zGEXY7IUh82yiwJTHZA0CYgsCg/gmwsCgJsLKKsL9SQsCrAmwsgoL8ibGUPYX6k2FkFATYrKKCybFYVXMJsQUAX6gCiwpf8AwgVh16FeyGrAnlbYcvm0VW7YfKl1QCpJDpeQnkjeti576RsBqSf/AD1HV9CnFNVWieRr6X9mAmmugmhttdUNU1/gDOr6EtNGrXkS/wBgiBp7Br3RLTQF2PmM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Xh+H5Iby5Od+SRy8P8Y4eWRRm5RbfWS0exj4zhXwympqn3povaSRl+nSW0tHl/GsC/SNxWoyT/wC/k9dZoT3BqS9DDjsKzYMkPOOifq2dPChjjilh1UpY7f5a/wBipKpGLzyycRByVKMVGvb/AJOnJumbcL6lrmg16GGH6qR0R6Uc245q8mEbyVTHJXBoMm4p0OP012A58Op0a5E1JMxl8mZ9DomlKCYBJc2Or7HH00dePoc+SNTegJt2CewVgt2tgaRba0i1dGcenU0XYCr2UR3K15AN6oQCAYrCwAx4iHMrW/Q4skaSfQ9JnNlxc1tLv0QX8xlF1o0x76IxTa13N8OpWK1Gk8LkrLwcM2qf5OnDBS6nUuTHHpsxrpjjXwvHJXZ18ksfDrE8rjjSrljoxy8Zy6icWTiJTe2VOo0nlWGE8eFvkl12cnbY3KwtIuI7vh+aUZVej38OR8qaPmuDf9Q+g4eXyKzFdeLp53JpS6HBxHw2KnzRTSfRo9BU9o1hyuNSEWx4WP4LilNSaTPWjwMeX59taWuiNHiS2v8ABonSpNsupjBYPDVRiZ5U72d8FzrZz8RBcrrqRcfG8RHk4zKl2m/5O1fNiT9Dj4uSl8Rz1052jp4aXNgp9jo8t9og+xjn1kTRsvqI4lLlvyKLj82L2DGTw8rjQ+k6sgz4hU0zTE+bHQs0bxsnh5VpsCo6lQ5RUnYppLJotU1uwjiXWxxW2AEKuL7lx/gAKKT2Uv4AC4AOoAQS3yxb8lZyT4138kFXqAFxKylxOWX91exk5OXVt+4AVlUHRvhltaADPJ14vUwy1ZrkuUbb7ABl2eflW2Yz1r0ABGKzb+YqLtAAqR28JjXNfqe3hdRQAZdeLohKo2bqa8NPlACNtIrmi32qxwxJ7YAVGsY8sW09eRy8TPljJ+SsAC3x8KsnPxEpvrKXMzt4d1OcV5gB2rxxd/MwypPGwAzBhg+o3nSl3AARdKcfR9Dmg2p2AEWt5JOq7ji/lX+QAsSP/9k='
}

# with open("1.jpg", "rb") as image_file:
#     encoded_string = base64.b64encode(image_file.read())
#     encoded_string = str(encoded_string, encoding='utf-8')
#     print(encoded_string)
#
#     model = FaceRecognition()
#     model.predict(encoded_string)

encoded_string = data.get('data')
encoded_string = encoded_string.split(',')[1]
model = FaceRecognition()
model.predict(encoded_string)
コード例 #13
0
#!/usr/bin/env python2

import numpy as np

from face_recognition import FaceRecognition

fr = FaceRecognition(load_model=False)

fr.train_network()
コード例 #14
0
ファイル: main.py プロジェクト: gnoya/face_recognition
from face_detection import FaceDetection
from face_recognition import FaceRecognition
from utils import read_image

if __name__ == "__main__":
    # Init the Face Detection and Face Recognition classes
    detection = FaceDetection()
    recognition = FaceRecognition()

    # Read the image
    image = read_image('./yolov3/data/samples/person.jpg')

    # Detect a face in the image (if many, returns the biggest one; if none, returns None)
    bounding_box = detection.detect(image)

    # bounding_box is a dictionary with parameters: x1, y1, x2, y2, width, height
    print(bounding_box)

    if bounding_box is not None:
        # Plot the bounding box on the image
        detection.plot(image, bounding_box)

        # Extract the face from the image
        face = recognition.extract(image, bounding_box)

        # Check if the face is from an employee, return True or False
        is_employee = recognition.recognize(face)

        if is_employee:
            print('Opening Door')
コード例 #15
0
ファイル: train.py プロジェクト: thenew01/NeuralNetworks
def main():
    # parsing arguments
    args = MyArgumentParser().get_arguments()
    neuralnetwork = FaceRecognition(epochs=args['epochs'],
                                    batch_size=args['batch'],
                                    image_width=args['image_width'],
                                    image_height=args['image_height'])
    neuralnetwork.create_img_generator()
    neuralnetwork.set_train_generator(train_dir=args['train'])
    neuralnetwork.set_valid_generator(valid_dir=args['valid'])

    # prepare the model
    if args['fine_tuning'][0]:
        neuralnetwork.set_face_recognition_model(
            pretrained_model=args['neuralnetwork'],
            weights='imagenet',
            trainable_parameters=args['fine_tuning'][0],
            num_trainable_parameters=args['fine_tuning'][1])
    else:
        neuralnetwork.set_face_recognition_model(
            pretrained_model=args['neuralnetwork'], weights='imagenet')
    # name for plot
    name = args['namedata']
    # train fit
    neuralnetwork.train_and_fit_model(name)
    # save model
    neuralnetwork.save_model_to_file(name=name,
                                     extension='.h5',
                                     export_image=False)
    # clear
    del neuralnetwork
コード例 #16
0
from face_recognition import FaceRecognition
from methods import FaceRecognitionMethod
from view import View

if __name__ == '__main__':
    view = View()
    face_recognition = FaceRecognition(view)
    face_recognition.run(FaceRecognitionMethod.DETECTOR
                         )  # Remove method if want use haar cascade
コード例 #17
0
ファイル: app.py プロジェクト: hienptit123/Web_Demo_Co_Ha
 def __init__(self):
     super(RunFaceID, self).__init__()
     self.face_detection = FaceDetection()
     self.face_recognition = FaceRecognition()
     self.arr_embeddings = pickle.load(open("data_embeddings", "rb"))
     self.labels = pickle.load(open("labels", "rb"))
コード例 #18
0
import os
from face_recognition import FaceRecognition

if __name__ == '__main__':
    model_name = "face_recognition.h5"
    image_path = 'test.jpg'
    face_recognition = FaceRecognition()
    face_recognition.training()
    face_recognition.save_model(model_name)
    # model = FaceRecognition.load_saved_model(os.path.join("model", model_name))
    #k = FaceRecognition.model_prediction(image_path, os.path.join("model", model_name),
    #                                     os.path.join("model", "face_recognition_class_names.npy"))
    #print(f"detected class is {k}")
コード例 #19
0
ファイル: app.py プロジェクト: surajkarki66/machine-learning
import os

from face_recognition import FaceRecognition
from face_detection import get_detected_face

if __name__ == "__main__":
    model_name = "face_recognition.h5"
    image_path = 'ronaldo.jpg'
    face_recognition = FaceRecognition()
    face_recognition.train()
    face_recognition.save(model_name)
# model = FaceRecognition.load_saved_model(os.path.join("model", model_name))
# f = FaceRecognition.model_predict(image_path, os.path.join("model", model_name),
#os.path.join("model", "face_recognition_class_names.npy"))
#print(f"This is {f}")
コード例 #20
0
import os
from face_recognition import FaceRecognition

if __name__ == '__main__':
    model_path = "model"
    image_path = 'test.jpg'
    face_recognition = FaceRecognition()
    face_recognition.training()
    face_recognition.save_model(model_name)
    model = FaceRecognition.load_saved_model(model_path)
    k = FaceRecognition.model_prediction(image_path, model_path)
    print(f"detected class is {k}")
コード例 #21
0
from face_recognition import FaceRecognition

file_path = "path_of_the_file"
key = "aws_key"
secret = "aws_secret"
token = "aws_token"

instance = FaceRecognition(file_path, key, secret, token)
results = instance.detection()

if isinstance(results, dict):
    print("The details of the candidate are as follows: ")
    for each_key in results.keys():
        print(each_key + '=' + str(results[each_key]))

else:
    print(results)
コード例 #22
0
import os
from face_recognition import FaceRecognition


if __name__ == '__main__':
    model_name = "face_recognition.h5"
    image_path = 'test.jpg'
    face_recognition = FaceRecognition()
    # face_recognition.training()
    # face_recognition.save_model(model_name)
    # model = FaceRecognition.load_saved_model(os.path.join("model", model_name))
    k = FaceRecognition.model_prediction(image_path, os.path.join("model", model_name),
                                         os.path.join("model", "face_recognition_class_names.npy"))
    print(f"detected class is {k}")
コード例 #23
0
if __name__ == '__main__':

    #classe que cria os alvos
    tempo = time.time()
    alvo = drawObj.Alvo()
    # conta quadros para desenhar novo alvo
    alvoQuadrosCount = 0
    # classe detecta fluxo optico
    fluxo = fluxo.Fluxo()
    # guarda estado atual da aplicacao
    estado = 0
    salvo = 'user.png'
    user1 = cv2.imread(salvo, 0)
    cam = Camera(1)
    faceTracker = roi.Detect()
    recon = FaceRecognition()
    contador = 0
    while True:
        #print 'estdo = ', estado
        # captura frame
        frame = cam.preprocessa()
        # detecta faces
        frame = faceTracker.detectar(**frame)
        #if 'gray' in frame.keys():
        #    cv2.imshow('gray', frame['gray'])
        #if 'roi_face' in frame.keys():
        #    cv2.imshow('roi_face', frame['roi_face'])
        if 'roi_eyes' in frame.keys():
            #cv2.imshow('roi_eyes', frame['roi_eyes'])
            estado = 1
        key = cv2.waitKey(10)
コード例 #24
0
import sys
import unittest

sys.path.append('../classes')
sys.path.append('../algorithms')
from report import Report
from auxiliary import Auxiliary
from face_recognition import FaceRecognition
from eigenfaces import Eigenfaces

auxiliary = Auxiliary()
algorithm = Eigenfaces()
faceRecog = FaceRecognition(algorithm, auxiliary)
report = Report(faceRecog)


class ReportSummaryTest(unittest.TestCase):
    def test1(self):
        wrong_report = Report(auxiliary)
        self.assertEqual(wrong_report.generate_report_summary(), "")

    def test2(self):
        self.assertEqual(report.generate_report_summary(), "")


if __name__ == '__main__':
    unittest.main()
コード例 #25
0
ファイル: image_box_tester.py プロジェクト: mashnoor/cc_cam
import cv2
from mtcnn import MTCNN
from face_recognition import FaceRecognition

detector = MTCNN()
fr = FaceRecognition()

image = cv2.cvtColor(cv2.imread("test.png"), cv2.COLOR_BGR2RGB)

print(fr.predict(image))
exit()

result = detector.detect_faces(image)

# Result is an array with all the bounding boxes detected. We know that for 'ivan.jpg' there is only one.
bounding_box = result[0]['box']
keypoints = result[0]['keypoints']

cv2.rectangle(
    image, (bounding_box[0], bounding_box[1]),
    (bounding_box[0] + bounding_box[2], bounding_box[1] + bounding_box[3]),
    (0, 155, 255), 2)

bounding_box = result[1]['box']
cv2.rectangle(
    image, (bounding_box[0], bounding_box[1]),
    (bounding_box[0] + bounding_box[2], bounding_box[1] + bounding_box[3]),
    (0, 155, 255), 2)

bounding_box = result[2]['box']
cv2.rectangle(