Example #1
0
def recognize_face(face_file, known_faces_dir):

    os.chdir(known_faces_dir)

    names = []
    encoded_faces = []

    for file in glob.glob("*.jpg"):

        # try to open and read cached data
        # if there is no *.enc file, generate it
        enc_file_name = file[0:-4] + ".enc"
        try:
            encoded = _utils.get_encoded(file, enc_file_name)

        except _utils.FaceNotFoundError:
            continue

        names.append(file)
        encoded_faces.append(encoded)

    unknown_face_file = face_recognition.load_image_file(face_file)

    try:
        unknown_face_encoded = face_recognition.face_encodings(unknown_face_file)[0]
    except IndexError:
        return str()

    results = face_recognition.compare_faces(encoded_faces, unknown_face_encoded)

    for i in range(0, len(results)):
        if results[i]:
            return names[i]

    return str()
Example #2
0
def test_image(image_to_check, tolerance=0.6):
    recognized_faces = []

    unknown_image = face_recognition.load_image_file(image_to_check)

    # Scale down image if it's giant so things run a little faster
    unknown_image = scale_image(unknown_image)

    unknown_encodings = face_recognition.face_encodings(unknown_image)
    face_landmarks_list = face_recognition.face_landmarks(unknown_image)
    face_locations = face_recognition.face_locations(unknown_image)

    pil_image = Image.fromarray(unknown_image)
    d = ImageDraw.Draw(pil_image)

    if not unknown_encodings:
        # print out fact that no faces were found in image
        print_result(image_to_check, "no_persons_found", None)

    else:
        for unknown_encoding, face_landmarks, face_location in zip(unknown_encodings, face_landmarks_list,
                                                                   face_locations):
            distances = face_recognition.face_distance(known_face_encodings, unknown_encoding)

            for distance, name in zip(distances, known_names):
                if distance <= tolerance:
                    print_result(image_to_check, name, distance)
                    recognized_faces.append(
                        {'name': name, 'dist': distance, 'landmarks': face_landmarks, 'face_location': face_location}
                    )
                else:
                    print_result(image_to_check, "unknown_person", None)

        for item in recognized_faces:
            face_landmarks = item['landmarks']
            face_location = item['face_location']
            # Print the location of each facial feature in this image
            # Let's trace out each facial feature in the image with a line!
            for facial_feature in face_landmarks.keys():
                print("The {} in this face has the following points: {}".format(facial_feature,
                                                                                face_landmarks[facial_feature]))
                d.line(face_landmarks[facial_feature], width=3)

            # Print the location of each face in this image
            top, right, bottom, left = face_location
            print(
                "A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom,
                                                                                                      right))
            d.rectangle(((left, top), (right, bottom)), outline=4)
            font = ImageFont.truetype("font/arial.ttf", size=30)
            title = item['name']
            text_size = d.textsize(title, font)
            d.text((left, bottom - text_size[1]), title, font=font, fill='white')

    pil_image.save("data/recognition_results/result.jpg")

    return recognized_faces
Example #3
0
def extract_faces(fname):
    image = face_recognition.load_image_file(fname)
    face_encodings = face_recognition.face_encodings(image)
    face_locations = face_recognition.face_locations(image)
    if len(face_locations) > 0:
        for face_location in face_locations:
            top,right,bottom,left = face_location
            face_image = image[top:bottom, left:right]
            pil_image = PIL.Image.fromarray(face_image)
    return {'encodings':face_encodings, 'locations':face_locations}
def trainFaces():
    print("---- Training Started ----")
    for root, dirs, files in os.walk("./faces"):
        for filename in files:
            file_result = filename.split("_")
            known_face_names.append(file_result[0])
            image = face_recognition.load_image_file("faces/"+filename)
            image_face_encoding = face_recognition.face_encodings(image)[0]
            known_face_encodings.append(image_face_encoding)
            print("Name: " + file_result[0])
    print("---- Training Completed ----")
Example #5
0
def face_recognition(frame, drawboxes=True):
    """ Perform face recognition using face_recognition package
    """
    global database, facedatabase, facedatabase_encodings, fraction

    # Define standard found state
    found = False

    # Initialize face database if not already initialized
    if (not database) or (not facedatabase) or (not facedatabase_encodings):
        database = list()
        # Search for known faces in faces/ directory
        for (_, _, filenames) in os.walk('faces'):
            database.extend(filenames)
            break
        # Populate face database and generate face encodings
        facedatabase = [fc.load_image_file(os.path.join('faces', name)) for name in database]
        facedatabase_encodings = [fc.face_encodings(face)[0] for face in facedatabase]
    
    # Create a resized copy of the frame in order to speed up processing
    small_frame = cv2.resize(frame, (0, 0), fx=fraction, fy=fraction)

    # Detect faces and generate their encodings
    face_locations = fc.face_locations(small_frame)
    face_encodings = fc.face_encodings(small_frame, face_locations)

    # Recognize faces if found
    if len(face_encodings) > 0:

        found = True

        # Recognize faces and determine their names
        face_names = []
        for face_encoding in face_encodings:
            match = fc.compare_faces(facedatabase_encodings, face_encoding, tolerance=0.5)
            try: name = database[match.index(True)].split('.')[0]
            except ValueError: name = "Unknown"
            face_names.append(name)
        
        # Draw a rectangle and name around recognized faces if required
        if drawboxes:
            for (top, right, bottom, left), name in zip(face_locations, face_names):
                if name != "Unknown":
                    top = int((1/fraction)*top - 16)
                    right = int((1/fraction)*right + 16)
                    bottom = int((1/fraction)*bottom + 16)
                    left = int((1/fraction)*left - 16)
                    cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                    cv2.rectangle(frame, (left-1, top - 20), (max(right+1, left+12*len(name)), top), (0, 0, 255), cv2.FILLED)
                    font = cv2.FONT_HERSHEY_DUPLEX
                    cv2.putText(frame, name, (left + 6, top - 6), font, 0.5, (255, 255, 255), 1)
    
    # Return frame and found state
    return frame, found
def train(train_dir, model_save_path = "", n_neighbors = None, knn_algo = 'ball_tree', verbose=False):
    """
    Trains a k-nearest neighbors classifier for face recognition.

    :param train_dir: directory that contains a sub-directory for each known person, with its name.

     (View in source code to see train_dir example tree structure)

     Structure:
        <train_dir>/
        ├── <person1>/
        │   ├── <somename1>.jpeg
        │   ├── <somename2>.jpeg
        │   ├── ...
        ├── <person2>/
        │   ├── <somename1>.jpeg
        │   └── <somename2>.jpeg
        └── ...
    :param model_save_path: (optional) path to save model of disk
    :param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified.
    :param knn_algo: (optional) underlying data structure to support knn.default is ball_tree
    :param verbose: verbosity of training
    :return: returns knn classifier that was trained on the given data.
    """
    X = []
    y = []
    for class_dir in listdir(train_dir):
        if not isdir(join(train_dir, class_dir)):
            continue
        for img_path in image_files_in_folder(join(train_dir, class_dir)):
            image = face_recognition.load_image_file(img_path)
            faces_bboxes = face_locations(image)
            if len(faces_bboxes) != 1:
                if verbose:
                    print("image {} not fit for training: {}".format(img_path, "didn't find a face" if len(faces_bboxes) < 1 else "found more than one face"))
                continue
            X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0])
            y.append(class_dir)


    if n_neighbors is None:
        n_neighbors = int(round(sqrt(len(X))))
        if verbose:
            print("Chose n_neighbors automatically as:", n_neighbors)

    knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')
    knn_clf.fit(X, y)

    if model_save_path != "":
        with open(model_save_path, 'wb') as f:
            pickle.dump(knn_clf, f)
    return knn_clf
    def process_image(self, image):
        """Process image."""
        # pylint: disable=import-error
        import face_recognition

        fak_file = io.BytesIO(image)
        fak_file.name = 'snapshot.jpg'
        fak_file.seek(0)

        image = face_recognition.load_image_file(fak_file)
        face_locations = face_recognition.face_locations(image)

        self.process_faces(face_locations, len(face_locations))
def detect_faces_in_image(file_stream):
    # Pre-calculated face encoding of Obama generated with face_recognition.face_encodings(img)
    known_face_encoding = [-0.09634063,  0.12095481, -0.00436332, -0.07643753,  0.0080383,
                            0.01902981, -0.07184699, -0.09383309,  0.18518871, -0.09588896,
                            0.23951106,  0.0986533 , -0.22114635, -0.1363683 ,  0.04405268,
                            0.11574756, -0.19899382, -0.09597053, -0.11969153, -0.12277931,
                            0.03416885, -0.00267565,  0.09203379,  0.04713435, -0.12731361,
                           -0.35371891, -0.0503444 , -0.17841317, -0.00310897, -0.09844551,
                           -0.06910533, -0.00503746, -0.18466514, -0.09851682,  0.02903969,
                           -0.02174894,  0.02261871,  0.0032102 ,  0.20312519,  0.02999607,
                           -0.11646006,  0.09432904,  0.02774341,  0.22102901,  0.26725179,
                            0.06896867, -0.00490024, -0.09441824,  0.11115381, -0.22592428,
                            0.06230862,  0.16559327,  0.06232892,  0.03458837,  0.09459756,
                           -0.18777156,  0.00654241,  0.08582542, -0.13578284,  0.0150229 ,
                            0.00670836, -0.08195844, -0.04346499,  0.03347827,  0.20310158,
                            0.09987706, -0.12370517, -0.06683611,  0.12704916, -0.02160804,
                            0.00984683,  0.00766284, -0.18980607, -0.19641446, -0.22800779,
                            0.09010898,  0.39178532,  0.18818057, -0.20875394,  0.03097027,
                           -0.21300618,  0.02532415,  0.07938635,  0.01000703, -0.07719778,
                           -0.12651891, -0.04318593,  0.06219772,  0.09163868,  0.05039065,
                           -0.04922386,  0.21839413, -0.02394437,  0.06173781,  0.0292527 ,
                            0.06160797, -0.15553983, -0.02440624, -0.17509389, -0.0630486 ,
                            0.01428208, -0.03637431,  0.03971229,  0.13983178, -0.23006812,
                            0.04999552,  0.0108454 , -0.03970895,  0.02501768,  0.08157793,
                           -0.03224047, -0.04502571,  0.0556995 , -0.24374914,  0.25514284,
                            0.24795187,  0.04060191,  0.17597422,  0.07966681,  0.01920104,
                           -0.01194376, -0.02300822, -0.17204897, -0.0596558 ,  0.05307484,
                            0.07417042,  0.07126575,  0.00209804]

    # Load the uploaded image file
    img = face_recognition.load_image_file(file_stream)
    # Get face encodings for any faces in the uploaded image
    unknown_face_encodings = face_recognition.face_encodings(img)

    face_found = False
    is_obama = False

    if len(unknown_face_encodings) > 0:
        face_found = True
        # See if the first face in the uploaded image matches the known face of Obama
        match_results = face_recognition.compare_faces([known_face_encoding], unknown_face_encodings[0])
        if match_results[0]:
            is_obama = True

    # Return the result as json
    result = {
        "face_found_in_image": face_found,
        "is_picture_of_obama": is_obama
    }
    return jsonify(result)
Example #9
0
def import_and_train_data():
    sql = '''INSERT INTO PERSONS (name, arr, picture) VALUES(?, ?, ?);'''
    cur = CONN.cursor()
    for picture_file in glob.glob('picturesTraining/*.jpg'):
        name = os.path.splitext(basename(picture_file))[0]
        if not cur.execute("SELECT name FROM persons WHERE name=?", (name, )).fetchone():
            print(name, ' is new.. Trains')
            with open(picture_file, 'rb') as input_file:
                ablob = input_file.read()
                image = face_recognition.load_image_file(picture_file)
                face_encoding = face_recognition.face_encodings(image)[0]
                CONN.execute(sql, [name, face_encoding, sqlite3.Binary(ablob)])
                print('done with: ', name)
        else:
            print(name, ' allready exist!')
    CONN.commit()
Example #10
0
    def reco_faces(self, class_face):
        def match_fono(location_, image_):
            top, right, bottom, left = location_
            # You can access the actual face itself like this:
            face_image = image_[top:bottom, left:right]
            try:
                unknown_face_encoding = face_recognition.face_encodings(face_image, num_jitters=NUM_JITTERS)[0]
                recos = face_recognition.compare_faces(
                    self.known_faces_list, unknown_face_encoding, tolerance=TOLERANCE)
            except:
                recos = []

            unk = "UNK{n}@unk{n}@00@"
            z = hash(location_)

            face_dict = {
                self.known_faces[index] if is_there else unk.format(n=z): location_ for index, is_there in
                enumerate(recos)}
            # face_dict = {
            #     self.known_faces[index]: location_ for index, is_there in
            #     enumerate(recos) if is_there}
            # print(
            #     "location Locs: {}  Top: {}, Left: {}, Bottom: {}, Right: {}"
            #     .format(face_dict, top, left, bottom, right))
            if any(("@unk" not in name) or ("@Fono-" in name) for name in face_dict.keys()):
                face_dict = {name: location for name, location in face_dict.items()
                             if ("@unk" not in name) or ("@Fono-" in name)}
            else:
                if face_dict.keys():
                    pil_image = Imger.fromarray(face_image)
                    pil_image.save("fono17_2/@Fono-{nome}.png".format(nome=face_dict.keys()[0]), "PNG")

            print("location Locs: {}  ".format(face_dict))
            return face_dict

        # Load the jpg file into a numpy array
        image = face_recognition.load_image_file(class_face)

        # Find all the faces in the image using a pre-trained convolutional neural network.
        # This method is more accurate than the default HOG model, but it's slower
        # unless you have an nvidia GPU and dlib compiled with CUDA extensions. But if you do,
        # this will use GPU acceleration and perform well.
        # See also: find_faces_in_picture.py
        face_locations = face_recognition.face_locations(image, number_of_times_to_upsample=NTU, model=MODEL)  # )
        fonos = {fono: locat for locat in face_locations for fono, locati in match_fono(locat, image).items() if fono}
        return fonos
Example #11
0
def scan_known_people(known_people_folder):
    for _file in image_files_in_folder(known_people_folder):
        file_path = os.path.basename(_file)
        print(file_path)
        basename = os.path.splitext(file_path)[0]
        img = face_recognition.load_image_file(_file)
        encodings = face_recognition.face_encodings(img)

        if len(encodings) > 1:
            print("WARNING: More than one face found in {}. Only considering the first face.".format(_file))

        if len(encodings) == 0:
            print("WARNING: No faces found in {}. Ignoring file.".format(_file))
        else:
            known_names.append(basename)
            known_face_encodings.append(encodings[0])
            print("{} found in {}".format(basename, file_path))
    def __init__(self, camera_entity, faces, name=None):
        """Initialize Dlib face identify entry."""
        # pylint: disable=import-error
        import face_recognition
        super().__init__()

        self._camera = camera_entity

        if name:
            self._name = name
        else:
            self._name = "Dlib Face {0}".format(
                split_entity_id(camera_entity)[1])

        self._faces = {}
        for face_name, face_file in faces.items():
            image = face_recognition.load_image_file(face_file)
            self._faces[face_name] = face_recognition.face_encodings(image)[0]
Example #13
0
    def __init__(self, imgpath):
        filelist = os.listdir(imgpath)

        self.face_names = []
        self.face_encodings = []
        for f in filelist:
            img = os.path.join(imgpath, f)
            if img.endswith(img_suffix) and os.path.isfile(img):
                image = face_recognition.load_image_file(img)

                if image is None:
                    print('image is None for file ',img)
                    continue

                face_encodings = face_recognition.face_encodings(image)[0]
                self.face_encodings.append(face_encodings)
                face_name = os.path.splitext(f)[0]
                self.face_names.append(face_name)
def find_and_save_face(web_file,face_file):
    # Load the jpg file into a numpy array
    image = face_recognition.load_image_file(web_file)
    print(image.dtype)
    # Find all the faces in the image
    face_locations = face_recognition.face_locations(image)

    print("I found {} face(s) in this photograph.".format(len(face_locations)))

    for face_location in face_locations:

        # Print the location of each face in this image
        top, right, bottom, left = face_location
        print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))

        # You can access the actual face itself like this:
        face_image = image[top:bottom, left:right]
        pil_image = Image.fromarray(face_image)
        pil_image.save(face_file)
Example #15
0
def get_image():
    image_b64 = request.values['imageBase64']

    file = io.BytesIO(urllib.request.urlopen(image_b64).read())
    image_PIL = Image.open(file)
    print ('image opened pil')
    #image_np = np.array(image_PIL)
    #print ('Image received: {}'.format(image_np.shape))
    image_PIL.save('static/img/rec.png')
    print ('Image received')

    image = face_recognition.load_image_file('static/img/rec.png')

    face_landmarks_list = face_recognition.face_landmarks(image)

    pil_image = Image.fromarray(image)

    prettyImg = makePretty(face_landmarks_list,pil_image,'static/img/')

    return ''
def predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6):
    """
    Recognizes faces in given image using a trained KNN classifier

    :param X_img_path: path to image to be recognized
    :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.
    :param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.
    :param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance
           of mis-classifying an unknown person as a known one.
    :return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].
        For faces of unrecognized persons, the name 'unknown' will be returned.
    """
    if not os.path.isfile(X_img_path) or os.path.splitext(X_img_path)[1][1:] not in ALLOWED_EXTENSIONS:
        raise Exception("Invalid image path: {}".format(X_img_path))

    if knn_clf is None and model_path is None:
        raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")

    # Load a trained KNN model (if one was passed in)
    if knn_clf is None:
        with open(model_path, 'rb') as f:
            knn_clf = pickle.load(f)

    # Load image file and find face locations
    X_img = face_recognition.load_image_file(X_img_path)
    X_face_locations = face_recognition.face_locations(X_img)

    # If no faces are found in the image, return an empty result.
    if len(X_face_locations) == 0:
        return []

    # Find encodings for faces in the test iamge
    faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_face_locations)

    # Use the KNN model to find the best matches for the test face
    closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)
    are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]

    # Predict classes and remove classifications that aren't within the threshold
    return [(pred, loc) if rec else ("unknown", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]
    def process_image(self, image):
        """Process image."""
        # pylint: disable=import-error
        import face_recognition

        fak_file = io.BytesIO(image)
        fak_file.name = 'snapshot.jpg'
        fak_file.seek(0)

        image = face_recognition.load_image_file(fak_file)
        unknowns = face_recognition.face_encodings(image)

        found = []
        for unknown_face in unknowns:
            for name, face in self._faces.items():
                result = face_recognition.compare_faces([face], unknown_face)
                if result[0]:
                    found.append({
                        ATTR_NAME: name
                    })

        self.process_faces(found, len(unknowns))
    def __init__(self, camera_entity, faces, name=None):
        """Initialize Dlib face identify entry."""
        # pylint: disable=import-error
        import face_recognition
        super().__init__()

        self._camera = camera_entity

        if name:
            self._name = name
        else:
            self._name = "Dlib Face {0}".format(
                split_entity_id(camera_entity)[1])

        self._faces = {}
        for face_name, face_file in faces.items():
            try:
                image = face_recognition.load_image_file(face_file)
                self._faces[face_name] = \
                    face_recognition.face_encodings(image)[0]
            except IndexError as err:
                _LOGGER.error("Failed to parse %s. Error: %s", face_file, err)
def get_face_images(picture_path):
    # Load the jpg file into a numpy array
    image = face_recognition.load_image_file(picture_path)

    # Find all the faces in the image using the default HOG-based model.
    # This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated.
    # See also: find_faces_in_picture_cnn.py
    face_locations = face_recognition.face_locations(image)

    print("I found {} face(s) in this photograph.".format(len(face_locations)))

    for face_location in face_locations:
        # Print the location of each face in this image
        top, right, bottom, left = face_location
        print(
            "A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom,
                                                                                                  right))

        # You can access the actual face itself like this:
        face_image = image[top:bottom, left:right]
        pil_image = Image.fromarray(face_image)
        print(picture_path)
        pil_image.save("{0}.jpg".format(picture_path[-7:-3]))
Example #20
0
def get_encoded(image_file, enc_file_name):

    # try to open and read cached data
    # if there is no *.enc file, generate it

    try:
        enc_file = open(enc_file_name, "rb")
        encoded_raw = enc_file.read()
        enc_file.close()

        if len(encoded_raw) == 0:      # file is empty? Treat it as not existing
            raise FileNotFoundError

        if encoded_raw == b"invalid":  # cache says we could not find face
            raise FaceNotFoundError

        encoded = pickle.loads(encoded_raw)

    except FileNotFoundError:          # no cache file, generate it
        print("Generating cache for file " + image_file)
        image = face_recognition.load_image_file(image_file)
        encodings = face_recognition.face_encodings(image)

        enc_file = open(enc_file_name, "ab")
        if len(encodings) > 0:
            encoded = face_recognition.face_encodings(image)[0]
            encoded_raw = pickle.dumps(encoded, protocol=0)
            enc_file.write(encoded_raw)
            enc_file.close()
        else:
            print("Could not find face")
            enc_file.write(b"invalid")
            enc_file.close()

            raise FaceNotFoundError

    return encoded
Example #21
0
    def load_image(self, file_path, name):
        if not os.path.exists(file_path):
            print("Image file not existed")
            return -1

        image_hash = self.compute_hash(file_path)
        if self.store.get_face_by_hash(image_hash):
            print("Face already recorded.")
            return -2

        try:
            image = face_recognition.load_image_file(file_path)
            face_encoding = face_recognition.face_encodings(image)[0]
        except Exception:
            print("Failed to recognition face")
            return -3

        face = {
            "name": name,
            "hash": image_hash,
            "face_encoding": list(face_encoding)
        }

        self.store.create_face(face)
def predict(X_img_path, knn_clf = None, model_save_path ="", DIST_THRESH = .5):
    """
    recognizes faces in given image, based on a trained knn classifier

    :param X_img_path: path to image to be recognized
    :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.
    :param model_save_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.
    :param DIST_THRESH: (optional) distance threshold in knn classification. the larger it is, the more chance of misclassifying an unknown person to a known one.
    :return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].
        For faces of unrecognized persons, the name 'N/A' will be passed.
    """

    if not isfile(X_img_path) or splitext(X_img_path)[1][1:] not in ALLOWED_EXTENSIONS:
        raise Exception("invalid image path: {}".format(X_img_path))

    if knn_clf is None and model_save_path == "":
        raise Exception("must supply knn classifier either thourgh knn_clf or model_save_path")

    if knn_clf is None:
        with open(model_save_path, 'rb') as f:
            knn_clf = pickle.load(f)

    X_img = face_recognition.load_image_file(X_img_path)
    X_faces_loc = face_locations(X_img)
    if len(X_faces_loc) == 0:
        return []

    faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_faces_loc)


    closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)

    is_recognized = [closest_distances[0][i][0] <= DIST_THRESH for i in range(len(X_faces_loc))]

    # predict classes and cull classifications that are not with high confidence
    return [(pred, loc) if rec else ("N/A", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_faces_loc, is_recognized)]
Example #23
0
from PIL import Image
import face_recognition

# Load the jpg file into a numpy array
image = face_recognition.load_image_file("images/abc38.JPG")

face_locations = face_recognition.face_locations(image)

print("I found {} face(s) in this photograph.".format(len(face_locations)))

for face_location in face_locations:

    # Print the location of each face in this image
    top, right, bottom, left = face_location
    print(
        "A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}"
        .format(top, left, bottom, right))

    # You can access the actual face itself like this:
    face_image = image[top:bottom, left:right]
    pil_image = Image.fromarray(face_image)
    pil_image.show()
Example #24
0
def main():
    # Starting of main
    print('in py af', flush=True)
    home = str(os.path.dirname(os.path.abspath(__file__))) + "/../../"
    print(home)
    file_names = glob.glob(home + "known_people/*.jp*g")

    known_encodings_file_path = home + "data/known_encodings_file.csv"
    people_file_path = home + "data/people_file.csv"

    # #For storing the encoding of a face
    known_encodings_file = Path(known_encodings_file_path)
    if known_encodings_file.is_file():
        known_encodings = np.genfromtxt(known_encodings_file, delimiter=',')
    else:
        known_encodings = []

    # #For Storing the name corresponding to the encoding
    people_file = Path(people_file_path)
    if people_file.is_file():
        people = np.genfromtxt(people_file, dtype='U', delimiter=',')
    else:
        people = []

    known_encodings_new = []
    people_new = []

    for file_name in file_names:
        temp = file_name.split('/')
        image_file_name = temp[-1]
        person_name = image_file_name.split('.')[0]
        if len(people) and person_name in people:
            # print("found {}".format(person_name))
            continue
        # print("Image name is {}".format(image_file_name.split('.')[0]))
        image_name = face_recognition.load_image_file(file_name)
        image_face_encoding = face_recognition.face_encodings(image_name)
        if len(image_face_encoding) == 1:
            face_encoding = image_face_encoding[0]
            known_encodings_new.append(face_encoding)
            people_new.append(person_name)

        else:
            print("NOTE: {} has more than one face.".format(image_file_name))

    known_encodings_save = np.array(known_encodings_new)
    people_save = np.array(people_new)

    #Print the new people added for debugging( CAUTION: Disable for large cases)
    # print("people = {} and {}".format(people_save, type(people_save)))


    # Save the face_encodings
    if known_encodings_file.is_file():
        with open(known_encodings_file, 'ab') as f:
            np.savetxt(f, known_encodings_save, delimiter=',')
    else:
        np.savetxt(known_encodings_file_path, known_encodings_save, delimiter=',')

    # Save the people names
    if people_file.is_file():
        with open(people_file, 'ab') as f:
            np.savetxt(f, people_save, delimiter=',', fmt="%s")
    else:
        np.savetxt(people_file_path, people_save, delimiter=',', fmt="%s")
Example #25
0
import face_recognition

image = face_recognition.load_image_file("my_picture.jpg")
face_locations = face_recognition.face_locations(image)

# face_locations is now an array listing the co-ordinates of each face!
Example #26
0
    ret,cap=video.read()
    gray = cv2.cvtColor(cap,0)
    cv2.imshow('livestream',gray)
    if cv2.waitKey(1) & 0xFF == ord('r'):
        file = "/home/aman-py/Desktop/Face_recognition/hell.jpg"
        cv2.imwrite(file, cap)
        break
video.release()
cv2.destroyAllWindows()
del(video)


import face_recognition
import tkinter
arr= {'amit':'Absent','ashok':'Absent','pp':'Absent','rakesh':'Absent','shubham':'Absent','mahipal':'Absent','aman':'Absent'}
aman = face_recognition.load_image_file('aman.jpg')
amit = face_recognition.load_image_file('amit.png')
ashok = face_recognition.load_image_file('ashok.jpg')
pp= face_recognition.load_image_file('pp.png')
rakesh= face_recognition.load_image_file('rakesh1.jpeg')
shubham = face_recognition.load_image_file('shubham.jpg')
mahipal = face_recognition.load_image_file('mahipal.jpg')
face_enco=[amit,ashok,pp,rakesh,shubham,mahipal,aman]
image =  face_recognition.load_image_file('hell.jpg')
im_enco = face_recognition.face_encodings(image)
ne_arr = []
for i in range(len(face_enco)):
    for j in range(len(im_enco)):
        pic = face_recognition.face_encodings(face_enco[i])
        check= face_recognition.compare_faces([im_enco[j]],pic[0],tolerance=0.57)
        if check == [True]:
Example #27
0
import os
import face_recognition
import sys
import pickle
import numpy
from collections import Counter
known_encoding = []
directory = input("Enter directory:")
if (len(directory) <= 1):
    print('Enter a valid path for KABOOM!!!!')
    exit(1)
else:
    image = face_recognition.load_image_file(directory)
    encoding = face_recognition.face_encodings(image)
    print('Original encoding:')
    print(encoding)
    print(
        '********************************************************************************'
    )
    res = pickle.load(open("encoding_info.pkl", "rb"))
    for i in res:
        a, b = i
        known_encoding.append(b)
import face_recognition

# Load the jpg files into numpy arrays
biden_image = face_recognition.load_image_file("biden.jpg")
obama_image = face_recognition.load_image_file("obama.jpg")
unknown_image = face_recognition.load_image_file("obama2.jpg")

# Get the face encodings for each face in each image file
# Since there could be more than one face in each image, it returns a list of encordings.
# But since I know each image only has one face, I only care about the first encoding in each image, so I grab index 0.
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]

known_faces = [
    biden_face_encoding,
    obama_face_encoding
]

# results is an array of True/False telling if the unknown face matched anyone in the known_faces array
results = face_recognition.compare_faces(known_faces, unknown_face_encoding)

print("Is the unknown face a picture of Biden? {}".format(results[0]))
print("Is the unknown face a picture of Obama? {}".format(results[1]))
print("Is the unknown face a new person that we've never seen before? {}".format(not True in results))
Example #29
0
def find_faces(path):
    image = face_recognition.load_image_file(path)
    face_locations = face_recognition.face_locations(image)

    return face_locations
Example #30
0
for jpg_file in all_jpg_files:
    file_path = jpg_file
    file_name = os.path.basename(file_path)
    name_only, extension = os.path.splitext(file_name)
    
    #use tesseract to extract text from the page and append to pages list
    image = Image.open(jpg_file)
    detected_text = pytesseract.image_to_string(image, lang="eng")
    if detected_text == '':
        image_text = ("Could not find text in the image")
    else:
	    image_text = (detected_text)

	#use face recognition to supply coords for faces
    image = face_recognition.load_image_file(jpg_file)
    face_location = face_recognition.face_locations(image)
    #append jpg file information to a dict in the pages list
    pages.append({
        "image_path": file_path,
        "image_path_docs": "docs/" + file_path,
        "title": name_only,
        "output_path": "docs/" + name_only + ".html",
        "output_filename": name_only + ".html",
        "image_text": image_text,
        'face_locations': face_location,
    })
    #copy file over to the /docs/images/ path
    shutil.copy(file_path, "docs/images/" + file_name)
    print('pages list item added for:', file_path)
Example #31
0
def recognize_image(image, known_face_names, known_face_encodings):
    recognized_faces = []

    print("Begining facial detection")
    image_f = face_recognition.load_image_file("./avatar/avatar.png")
    face_locations = face_recognition.face_locations(image_f)
    print("Completed facial detection")
    print("Known Names: ", known_face_names)
    face_encodings = face_recognition.face_encodings(image_f, face_locations)

    # Convert to PIL format
    pil_image = Image.fromarray(image_f)

    # Create a ImageDraw instance
    draw = ImageDraw.Draw(pil_image)
    fontsize = 50
    font = ImageFont.truetype("arial.ttf", fontsize)

    # Loop through faces in test image
    for(top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        # matches is list of boolean values representing which faces in known_face_encodings the current is "familiar" with
        matches = face_recognition.compare_faces(known_face_encodings, face_encoding) 
        # print("What is face encodings?: ", face_encoding)
        print("What is matches :???: ", matches)
        # print("is encodings a numpy array?: ", type(face_encoding) )
        #Note: face_encoding is a numpy array of size (128,) 
        name = "Unknown Person"
        diff_list = best_match (face_encoding, known_face_encodings)
        print("Differences: ", diff_list)
        # find index with minimum difference
        min_index = 0
        print("Min_VAl?: ", min_index)
        min_val = diff_list[min_index]
        # find index with minimum
        for dic in range(len(diff_list)):
            if diff_list[dic] < min_val:
                min_index = dic
                min_val = diff_list[dic]
        # only if numpy also says its "similar" 
        # and make sure the diff is at least 4.4 or under
        #  and (min_val <= 4.4)
        min_threshold = 10
        # if(matches[min_index]):
            # name = known_face_names[min_index]
        if(matches[min_index]) and (min_val <= min_threshold):
            name = known_face_names[min_index]

        if name != "Unknown Person" and name not in recognized_faces:
            recognized_faces.append(name)
        print("WE HAVE RECOGNIZED: ", name)
        print("With diff_value: ", min_val)

        # Draw box
        draw.rectangle(((left, top), (right, bottom)), outline=(255,255,0))
        # Draw label
        text_width, text_height = draw.textsize(name)
        text_height = text_height*4
        draw.rectangle(((left,bottom - text_height - 10), (right, bottom)), fill=(255,255,0), outline=(255,255,0))
        draw.text((left + 6, bottom - text_height - 5), name, font=font, fill=(0,0,0))
        # draw.text((5, 5), name, fill=(0,0,0))

    del draw

    # Uncomment to Display image:
    # pil_image.show()

    # Save image
    pil_image.save('./avatar/detected.png')
    print("\n\n\n\n\n")
    return face_locations, recognized_faces
Example #32
0
fpath = args.infolder
# Max number of people to embed
im_total = 1000
names = []
embeddings = []
# Go through image folder
for i, npath in enumerate(os.listdir(fpath)):
    # Stop and max number
    if i == im_total:
        break
    embedding = np.zeros((128, ))
    num_im = 0
    # For every image to a person
    for ipath in os.listdir(os.path.join(fpath, npath)):
        # Obtain face embedding
        face_image = face_recognition.load_image_file(
            os.path.join(fpath, npath, ipath))
        face_embedding = face_recognition.face_encodings(face_image)
        # If face exists, add to embedding vector
        if face_embedding:
            embedding = np.add(embedding, face_embedding[0])
            num_im += 1
    # Find average face embedding for the person and add to lists
    if num_im > 0:
        embedding = np.divide(embedding, num_im)
        embeddings.append(embedding)
        names.append(npath)
        print('Embedded', npath)
    # No images/faces found
    else:
        print('Not embedded', npath)
print("connecting to \"%s\" on %s" % (name, host))

# Create the client socket
sock = BluetoothSocket(RFCOMM)
sock.connect((host, port))
# Get a reference to the Raspberry Pi camera.
# If this fails, make sure you have a camera connected to the RPi and that you
# enabled your camera in raspi-config and rebooted first.
camera = picamera.PiCamera()
camera.resolution = (320, 240)
output = np.empty((240, 320, 3), dtype=np.uint8)

# Load a sample picture and learn how to recognize it.
print("Loading known face image(s)")
#obama_image = face_recognition.load_image_file("obama_small.jpg")
obama_image = face_recognition.load_image_file("jasper.png")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
o_image = face_recognition.load_image_file("harry.png")
o_face_encoding = face_recognition.face_encodings(o_image)[0]
# Initialize some variables
face_locations = []
face_encodings = []

while True:
    print("Capturing image.")
    # Grab a single frame of video from the RPi camera as a numpy array
    camera.capture(output, format="rgb")

    # Find all the faces and face encodings in the current frame of video
    face_locations = face_recognition.face_locations(output)
    print("Found {} faces in image.".format(len(face_locations)))
Example #34
0
import cv2
import face_recognition
import sqlite3


input_video = cv2.VideoCapture(0)
peter_image = face_recognition.load_image_file("Image from iOS.jpg")
peter_face_encoding = face_recognition.face_encodings(peter_image)[0]


bayne_image = face_recognition.load_image_file("IMG_20190807_162611.jpg")
bayne_face_encoding = face_recognition.face_encodings(bayne_image)[0]


faheem_image = face_recognition.load_image_file("faheem.jpg")
faheem_face_encoding = face_recognition.face_encodings(faheem_image)[0]

priya_image = face_recognition.load_image_file("priya.jpg")
priya_face_encoding = face_recognition.face_encodings(priya_image)[0]

rahul_image = face_recognition.load_image_file("rahul.jpg")
rahul_face_encoding = face_recognition.face_encodings(rahul_image)[0]




known_faces = [
    peter_face_encoding,
    bayne_face_encoding,
    faheem_face_encoding,
    priya_face_encoding,
import face_recognition
from PIL import Image, ImageDraw

# This is an example of running face recognition on a single image
# and drawing a box around each person that was identified.

# Load a sample picture and learn how to recognize it.
obama_image = face_recognition.load_image_file("obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]

# Load a second sample picture and learn how to recognize it.
biden_image = face_recognition.load_image_file("biden.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [obama_face_encoding, biden_face_encoding]
known_face_names = ["Ganesh Attarde", "Joe Biden"]

# Load an image with an unknown face
unknown_image = face_recognition.load_image_file("two_people.jpg")

# Find all the faces and face encodings in the unknown image
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)

# Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library
# See http://pillow.readthedocs.io/ for more about PIL/Pillow
pil_image = Image.fromarray(unknown_image)
# Create a Pillow ImageDraw Draw instance to draw with
draw = ImageDraw.Draw(pil_image)
Example #36
0
import face_recognition
from PIL import Image, ImageDraw
import numpy as np

# Load a sample picture and learn how to recognize it.
sanjay_image = face_recognition.load_image_file("Sanjay.jpg")
sanjay_face_encoding = face_recognition.face_encodings(sanjay_image)[0]

# Load a second sample picture and learn how to recognize it.
rishab_image = face_recognition.load_image_file("Rishab.jpg")
rishab_face_encoding = face_recognition.face_encodings(rishab_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [obama_face_encoding, biden_face_encoding]
known_face_names = ["Sanjay", "Rishab"]

# Load an image with an unknown face
unknown_image = face_recognition.load_image_file("f1.jpg")

# Find all the faces and face encodings in the unknown image
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)

pil_image = Image.fromarray(unknown_image)
draw = ImageDraw.Draw(pil_image)

# Loop through each face found in the unknown image
for (top, right, bottom, left), face_encoding in zip(face_locations,
                                                     face_encodings):
    # See if the face is a match for the known face(s)
    matches = face_recognition.compare_faces(known_face_encodings,
from PIL import Image, ImageDraw
import face_recognition

# Load the jpg file into a numpy array
image = face_recognition.load_image_file("1.jpg")

# Find all facial features in all the faces in the image
face_landmarks_list = face_recognition.face_landmarks(image)

for face_landmarks in face_landmarks_list:
    pil_image = Image.fromarray(image)
    d = ImageDraw.Draw(pil_image, 'RGBA')

    # Make the eyebrows into a nightmare
    d.polygon(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 128))
    d.polygon(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 128))
    d.line(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 150), width=5)
    d.line(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 150), width=5)

    # Gloss the lips
    d.polygon(face_landmarks['top_lip'], fill=(150, 0, 0, 128))
    d.polygon(face_landmarks['bottom_lip'], fill=(150, 0, 0, 128))
    d.line(face_landmarks['top_lip'], fill=(150, 0, 0, 64), width=8)
    d.line(face_landmarks['bottom_lip'], fill=(150, 0, 0, 64), width=8)

    # Sparkle the eyes
    d.polygon(face_landmarks['left_eye'], fill=(255, 255, 255, 30))
    d.polygon(face_landmarks['right_eye'], fill=(255, 255, 255, 30))

    # Apply some eyeliner
    d.line(face_landmarks['left_eye'] + [face_landmarks['left_eye'][0]],
from PIL import Image, ImageDraw
import face_recognition

# Load the jpg file into a numpy array
image = face_recognition.load_image_file("two_people.jpg")

# Find all facial features in all the faces in the image
face_landmarks_list = face_recognition.face_landmarks(image)

print("I found {} face(s) in this photograph.".format(len(face_landmarks_list)))

# Create a PIL imagedraw object so we can draw on the picture
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)

for face_landmarks in face_landmarks_list:

    # Print the location of each facial feature in this image
    for facial_feature in face_landmarks.keys():
        print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature]))

    # Let's trace out each facial feature in the image with a line!
    for facial_feature in face_landmarks.keys():
        d.line(face_landmarks[facial_feature], width=5)

# Show the picture
pil_image.show()
Example #39
0
import os
import glob

video_capture = cv2.VideoCapture(0)

known_face_encodings = []
known_face_names = []
dirname = os.path.dirname(__file__)
path = os.path.join(dirname, 'faces/')

list_of_files = [f for f in glob.glob(path + '*.png')]
number_files = len(list_of_files)
names = list_of_files.copy()

for i in range(number_files):
    globals()['image_{}'.format(i)] = face_recognition.load_image_file(
        list_of_files[i])
    globals()['image_encoding_{}'.format(i)] = face_recognition.face_encodings(
        globals()['image_{}'.format(i)])[0]
    known_face_encodings.append(globals()['image_encoding_{}'.format(i)])

    names[i] = names[i].replace("faces/", "").replace(".png", "")
    known_face_names.append(names[i])

face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:

    ret, frame = video_capture.read()
Example #40
0
import face_recognition
from PIL import Image, ImageDraw

image_of_megan = face_recognition.load_image_file(
    './images/known/megan_fox.jpg')
megan_face_encoding = face_recognition.face_encodings(image_of_megan)[0]

image_of_shia = face_recognition.load_image_file(
    './images/known/shia_labeouf.jpg')
shia_face_encoding = face_recognition.face_encodings(image_of_shia)[0]

# Создаем массив с кодировками и именами
known_face_encodings = [megan_face_encoding, shia_face_encoding]

known_face_names = ["Megan Fox", "Shia Labeouf"]

# Загрузка тестового изображния на котором будут искаться закодированные лица
test_image = face_recognition.load_image_file(
    './images/people/megan_fox_lebaf.jpg')

# Нахождение лиц на тестовом изображении
face_locations = face_recognition.face_locations(test_image)
face_encodings = face_recognition.face_encodings(test_image, face_locations)

# Конвертируем изображние в формат PIL, чтобы была возможность рисовать на изображении
pil_image = Image.fromarray(test_image)

# Создаем экземпляр ImageDraw, чтобы рисовать на изображении
draw = ImageDraw.Draw(pil_image)

# Проходимся циклом по лицам в тестовом изображении (test_image)
Example #41
0
# coding: utf-8
from PIL import Image
import face_recognition
import csv
img_dir = "/Users/hezheng/Downloads/img/"
with open("img_list.csv", "r", encoding="utf-8") as csvfile:
    read = csv.reader(csvfile)
    true_datacsv = open("true_img_list.csv","w")
    false_datacsv = open("false_img_list.csv","w")
    for i in read:
        image = face_recognition.load_image_file(i[0])
        face_locations = face_recognition.face_locations(image)
        if len(face_locations) > 0:
            print("{} face(s) in {}.".format(len(face_locations),i[0]))
            true_datacsv = open("true_img_list.csv", "a", newline="")
            csvwriter = csv.writer(true_datacsv, dialect=("excel"))
            csvwriter.writerow(i)
        else:
            false_datacsv = open("false_img_list.csv", "a", newline="")
            csvwriter = csv.writer(false_datacsv, dialect=("excel"))
            csvwriter.writerow(i)
    true_datacsv.close()
    false_datacsv.close()

# image = face_recognition.load_image_file(img_dir+img_name)

# Find all the faces in the image
# face_locations = face_recognition.face_locations(image)
#
# print("I found {} face(s) in this photograph.".format(len(face_locations)))
Example #42
0
def run_single(image_path: str):
    image = face_recognition.load_image_file(image_path)
    face_locations = face_recognition.face_locations(image, model='cnn')
    return face_locations
Example #43
0
import face_recognition
import cv2
from face_recognition.api import face_encodings
import numpy as np
import os
from dotenv import load_dotenv

load_dotenv()

faces_dir = os.getenv('faces_directory')

known_faces = []
names = []
for filename in os.listdir(faces_dir):
    loadface = face_recognition.load_image_file(faces_dir + filename)
    encoding = face_recognition.face_encodings(loadface)[0]
    known_faces.append(encoding)
    names.append(filename[:len(filename) - 4])

video_capture = cv2.VideoCapture(0)
fps = video_capture.get(cv2.CAP_PROP_FPS)
w = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))

# fourcc = cv2.VideoWriter_fourcc(*'XVID')
# output = cv2.VideoWriter("output_{}.avi".format(src[:len(src)-4]),fourcc, fps, (w,h))

face_locations = []
face_encodes = []
face_name = []
process_this_frame = True
Example #44
0
import face_recognition

obama_image = face_recognition.load_image_file("obama.jpeg")
merkel_image = face_recognition.load_image_file("merkel.jpg")
grandpa_image = face_recognition.load_image_file("grandpa.jpg")
me2_image = face_recognition.load_image_file("me2.jpg")
me_image = face_recognition.load_image_file("me.jpg")

obama_image_encoding = face_recognition.face_encodings(obama_image)
merkel_image_encoding = face_recognition.face_encodings(merkel_image)
grandpa_image_encoding = face_recognition.face_encodings(grandpa_image)
me2_image_encoding = face_recognition.face_encodings(me2_image)
me_image_encoding = face_recognition.face_encodings(me_image)

known_faces = [
    obama_image_encoding[0], merkel_image_encoding[0], me2_image_encoding[0],
    grandpa_image_encoding[0]
]

recognition_result = face_recognition.compare_faces(known_faces,
                                                    me_image_encoding[0])

faces_txt = ['obama', 'merkel', 'me', 'grandpa']
print('Is the face even present in a current database? {0}'.format(
    True in recognition_result))
for i, result in enumerate(recognition_result):
    print('Is the unknown face a picture of {0} ? - {1}'.format(
        faces_txt[i], result))

print("End of the program")
Example #45
0
def videotest(filename):
    video_capture = cv2.VideoCapture(filename)
    length = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = int(video_capture.get(cv2.CAP_PROP_FPS))

    sai = face_recognition.load_image_file("2.jpg")
    sfencoding = face_recognition.face_encodings(sai)[0]

    dhoni = face_recognition.load_image_file("1.jpg")
    dfencoding = face_recognition.face_encodings(dhoni)[0]

    virat = face_recognition.load_image_file("3.jpg")
    vfencoding = face_recognition.face_encodings(virat)[0]

    modi = face_recognition.load_image_file("4.jpg")
    mfencoding = face_recognition.face_encodings(modi)[0]

    prateek = face_recognition.load_image_file("prateek.jpg")
    pfencoding = face_recognition.face_encodings(prateek)[0]

    harmesh = face_recognition.load_image_file("harmesh.jpg")
    hfencoding = face_recognition.face_encodings(harmesh)[0]

    vishnu = face_recognition.load_image_file("vishnu.jpg")
    nvencoding = face_recognition.face_encodings(vishnu)[0]

    robert = face_recognition.load_image_file("robertdowney jr.jpg")
    rbjencoding = face_recognition.face_encodings(robert)[0]

    harry = face_recognition.load_image_file("daniel radcliffe.jpg")
    harryencoding = face_recognition.face_encodings(harry)[0]

    hermoine = face_recognition.load_image_file("emma watson.jpg")
    herencoding = face_recognition.face_encodings(hermoine)[0]

    rupert = face_recognition.load_image_file("ront1.jpg")
    ronencoding = face_recognition.face_encodings(rupert)[0]

    known_face_encodings = [
        sfencoding, dfencoding, vfencoding, mfencoding, pfencoding, hfencoding,
        nvencoding, rbjencoding, harryencoding, herencoding, ronencoding
    ]
    known_face_names = [
        "sai", "DHONI", "virat", "modi", "prateek", "harmesh", "vishnu",
        "robert downey jr.", "daniel radcliffe", "emma watson", "rupert grint"
    ]

    width = int(video_capture.get(3))  # float
    height = int(video_capture.get(4))
    fourcc = cv2.VideoWriter_fourcc(*'vp80')
    PATH = '/home/saisri/projectcopy_5/project/demo.webm'
    out = cv2.VideoWriter(PATH, fourcc, fps, (width, height))
    for i in range(1, length - 1):

        ret, frame = video_capture.read()
        rgb_frame = frame[:, :, ::-1]
        face_locations = face_recognition.face_locations(rgb_frame)
        face_encodings = face_recognition.face_encodings(
            rgb_frame, face_locations)

        for (top, right, bottom,
             left), face_encoding in zip(face_locations, face_encodings):
            matches = face_recognition.compare_faces(known_face_encodings,
                                                     face_encoding)
            name = "Unknown"
            face_distances = face_recognition.face_distance(
                known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]

            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.rectangle(frame, (left, bottom - 10), (right, bottom + 10),
                          (10, 10, 10), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, name, (left + 2, bottom), font, 0.4,
                        (255, 255, 255), 1)

        print()
        sys.stdout.write(f"writing...{int((i/length)*100)+1}%")
        sys.stdout.flush()
        out.write(frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    video_capture.release()
    out.release()
    cv2.destroyAllWindows()
    return PATH
Example #46
0
import cv2
import face_recognition as fr
import numpy as np

original_image = cv2.imread(
    '/home/sahgan/Desktop/quarantineStuff/Udemy/ComputerVisionFacialRecognition/images/22birthday.jpg'
)

sah = fr.load_image_file(
    '/home/sahgan/Desktop/quarantineStuff/Udemy/ComputerVisionFacialRecognition/images/sg.jpg'
)
encSah = fr.face_encodings(sah)[0]
shamm = fr.load_image_file(
    '/home/sahgan/Desktop/quarantineStuff/Udemy/ComputerVisionFacialRecognition/images/shamm1.jpg'
)
encShamm = fr.face_encodings(shamm)[0]
akhil = fr.load_image_file(
    '/home/sahgan/Desktop/quarantineStuff/Udemy/ComputerVisionFacialRecognition/images/akhil1.jpg'
)
encAkhil = fr.face_encodings(akhil)[0]
niharika = fr.load_image_file(
    '/home/sahgan/Desktop/quarantineStuff/Udemy/ComputerVisionFacialRecognition/images/niharika1.jpg'
)
encNiharika = fr.face_encodings(niharika)[0]

shru = fr.load_image_file(
    '/home/sahgan/Desktop/quarantineStuff/Udemy/ComputerVisionFacialRecognition/images/shru.jpg'
)
encShru = fr.face_encodings(shru)[0]
mum = fr.load_image_file(
    '/home/sahgan/Desktop/quarantineStuff/Udemy/ComputerVisionFacialRecognition/images/mum.jpg'
""" 人脸识别 """
import face_recognition
import cv2 as cv
import os
import pickle

print(cv.__version__)

Encodings = []
Names = []
image_dir = '/home/jetson/Desktop/jetson-git/demoImages/known'
# os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。
for root, dirs, files in os.walk(image_dir):
    for file in files:
        fullPath = os.path.join(root, file)
        print(fullPath)
        # 从后往前搜索.分割后缀名
        name = os.path.splitext(file)[0]
        print(name)
        person = face_recognition.load_image_file(fullPath)
        encoding = face_recognition.face_encodings(person)
        Encodings.append(encoding)
        Names.append(name)
    print(Names)
    # 备份
    with open('train.pkl', "wb") as f:
        pickle.dump(Names, f)
        pickle.dump(Encodings, f)
Example #48
0
import glob
import os

os.chdir("C:\ProgramData\AttendanceSys\images")

known_images_names = []
known_images = []
known_encodings = []
 # this will be the database access
for file in glob.glob("*.png"):
  if file=="ImageToMark.png":
    continue
  known_images_names.append(file)
# print (known_images_names)
for file in known_images_names:
  known_images.append(face_recognition.load_image_file(file))
# print (known_images)
for filename in known_images:
  e = face_recognition.face_encodings(filename)
  if (len(e) > 0):
    known_encodings.append(face_recognition.face_encodings(filename)[0]) 
# print (known_encodings)
 #this will be the image received from c#
unknown_image1 = face_recognition.load_image_file("ImageToMark.png")

result = [False]
e = face_recognition.face_encodings(unknown_image1)
if (len(e) > 0):
  unknown_encoding1 = face_recognition.face_encodings(unknown_image1)[0]
  # print (unknown_encoding1)
  for x in known_encodings:
Example #49
0
import _thread
from http import server  #need to impliment server
import sys
import psutil
from queue import Queue
q = Queue()

known_face_encodings = []
known_face_names = []
# Will open text file of names/images and add line by line to model
with open('enrolled.txt') as fp:
    for person in fp:
        data = person.split("^^")
        known_face_names.append(data[0])

        image = face_recognition.load_image_file(os.getcwd() + "/Images/" +
                                                 data[1].replace("\n", ""))

        image_encoding = face_recognition.face_encodings(image)[0]
        known_face_encodings.append(image_encoding)

face_locations = []
face_encodings = []
face_names = []

#HTML for website
PAGE = """\
<html>
<head>
<title>Pi Camera Video Feed</title>
</head>
<body>
Example #50
0
@decription:将图片人脸框出并保存
"""

from PIL import Image
import face_recognition
import os

# for (int i = 1; i <= 10; i++)
list = os.listdir("/home/260240/PycharmProjects/glasses_detection/noGlass")
for i in range(0, 10001):
    imgName = os.path.basename(list[i])
    if os.path.splitext(imgName)[1] != ".jpg":
        continue

    image = face_recognition.load_image_file(imgName)

    face_locations = face_recognition.face_locations(image)

    for face_location in face_locations:

        # Print the location of each face in this image
        top, right, bottom, left = face_location
        # print("A face is located at pixel location Top: {},
        #  Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))

        # You can access the actual face itself like this:
        width = right - left
        height = bottom - top
        if width > height:
            right -= (width - height)
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False):
    """
    Trains a k-nearest neighbors classifier for face recognition.

    :param train_dir: directory that contains a sub-directory for each known person, with its name.

     (View in source code to see train_dir example tree structure)

     Structure:
        <train_dir>/
        ├── <person1>/
        │   ├── <somename1>.jpeg
        │   ├── <somename2>.jpeg
        │   ├── ...
        ├── <person2>/
        │   ├── <somename1>.jpeg
        │   └── <somename2>.jpeg
        └── ...

    :param model_save_path: (optional) path to save model on disk
    :param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified
    :param knn_algo: (optional) underlying data structure to support knn.default is ball_tree
    :param verbose: verbosity of training
    :return: returns knn classifier that was trained on the given data.
    """
    X = []
    y = []

    # Loop through each person in the training set
    for class_dir in os.listdir(train_dir):
        if not os.path.isdir(os.path.join(train_dir, class_dir)):
            continue

        # Loop through each training image for the current person
        for img_path in image_files_in_folder(os.path.join(train_dir, class_dir)):
            image = face_recognition.load_image_file(img_path)
            face_bounding_boxes = face_recognition.face_locations(image)

            if len(face_bounding_boxes) != 1:
                # If there are no people (or too many people) in a training image, skip the image.
                if verbose:
                    print("Image {} not suitable for training: {}".format(img_path, "Didn't find a face" if len(face_bounding_boxes) < 1 else "Found more than one face"))
            else:
                # Add face encoding for current image to the training set
                X.append(face_recognition.face_encodings(image, known_face_locations=face_bounding_boxes)[0])
                y.append(class_dir)

    # Determine how many neighbors to use for weighting in the KNN classifier
    if n_neighbors is None:
        n_neighbors = int(round(math.sqrt(len(X))))
        if verbose:
            print("Chose n_neighbors automatically:", n_neighbors)

    # Create and train the KNN classifier
    knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')
    knn_clf.fit(X, y)

    # Save the trained KNN classifier
    if model_save_path is not None:
        with open(model_save_path, 'wb') as f:
            pickle.dump(knn_clf, f)

    return knn_clf
def train(train_dir,
          model_save_path=None,
          n_neighbors=None,
          knn_algo='ball_tree',
          verbose=False):
    """
    Trains a k-nearest neighbors classifier for face recognition.

    :param train_dir: directory that contains a sub-directory for each known person, with its name.

     (View in source code to see train_dir example tree structure)

     Structure:
        <train_dir>/
        ├── <person1>/
        │   ├── <somename1>.jpeg
        │   ├── <somename2>.jpeg
        │   ├── ...
        ├── <person2>/
        │   ├── <somename1>.jpeg
        │   └── <somename2>.jpeg
        └── ...

    :param model_save_path: (optional) path to save model on disk
    :param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified
    :param knn_algo: (optional) underlying data structure to support knn.default is ball_tree
    :param verbose: verbosity of training
    :return: returns knn classifier that was trained on the given data.
    """
    X = []
    y = []

    # Loop through each person in the training set
    for class_dir in os.listdir(train_dir):
        if not os.path.isdir(os.path.join(train_dir, class_dir)):
            continue

        # Loop through each training image for the current person
        for img_path in image_files_in_folder(
                os.path.join(train_dir, class_dir)):
            image = face_recognition.load_image_file(img_path)
            face_bounding_boxes = face_recognition.face_locations(image)

            if len(face_bounding_boxes) != 1:
                # If there are no people (or too many people) in a training image, skip the image.
                if verbose:
                    print("Image {} not suitable for training: {}".format(
                        img_path,
                        "Didn't find a face" if len(face_bounding_boxes) < 1
                        else "Found more than one face"))
            else:
                # Add face encoding for current image to the training set
                X.append(
                    face_recognition.face_encodings(
                        image, known_face_locations=face_bounding_boxes)[0])
                y.append(class_dir)

    # Determine how many neighbors to use for weighting in the KNN classifier
    if n_neighbors is None:
        n_neighbors = int(round(math.sqrt(len(X))))
        if verbose:
            print("Chose n_neighbors automatically:", n_neighbors)

    # Create and train the KNN classifier
    knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors,
                                             algorithm=knn_algo,
                                             weights='distance')
    knn_clf.fit(X, y)

    # Save the trained KNN classifier
    if model_save_path is not None:
        with open(model_save_path, 'wb') as f:
            pickle.dump(knn_clf, f)

    return knn_clf
Example #53
0
from PIL import Image
import face_recognition
import numpy as np

# Load the jpg file into a numpy array
unknown_image = face_recognition.load_image_file("./unknown_pics/unknown.jpg")

angel_image = face_recognition.load_image_file("./known_ppl/Angel Gao.jpg")
angel_face_encoding = face_recognition.face_encodings(angel_image)[0]

melissa_image = face_recognition.load_image_file("./known_ppl/Melissa Pan.jpg")
melissa_face_encoding = face_recognition.face_encodings(melissa_image)[0]

known_face_encodings = [angel_face_encoding, melissa_face_encoding]

known_face_names = ["Angel Gao", "Melissa Pan"]

# Find all the faces in the image using the default HOG-based model.
# This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated.
# See also: find_faces_in_picture_cnn.py
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)

print("I found {} face(s) in this photograph.".format(len(face_locations)))

# for face_location in face_locations:

#     # Print the location of each face in this image
#     top, right, bottom, left = face_location
#     print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
"""
Author: Kyle Mabry
This is a simple script to be used as a sanity check. It just makes sure that everything is working on the
face_recognition side of things.
Last edit made: 08/29/2020
"""

import face_recognition

# Load the images we're going to be comapring.
known_image = face_recognition.load_image_file("kyle.jpg")
unknown_image = face_recognition.load_image_file("unknown.jpg")
unknown_image1 = face_recognition.load_image_file("unknown1.jpg")

# Encode the images.
known_face_encoding = face_recognition.face_encodings(known_image)[0]
unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]
unknown_face_encoding1 = face_recognition.face_encodings(unknown_image1)[0]

# Make a list of known faces.
known_images = [unknown_face_encoding, unknown_face_encoding1]

# Get the results of our comparison.
results = face_recognition.compare_faces(known_images, known_face_encoding)

# Print the results for the user to see.
print("Results: " + str(results))

Example #55
0
    people = np.genfromtxt(people_file, dtype='U',delimiter=',')
else:
    people = []

known_encodings_new = []
people_new = []

for file_name in file_names:
    temp = file_name.split('/')
    image_file_name = temp[-1]
    person_name = image_file_name.split('.')[0]
    if len(people) and person_name in people:
        # print("found {}".format(person_name))
        continue
    # print("Image name is {}".format(image_file_name.split('.')[0]))
    image_name = face_recognition.load_image_file(file_name)
    image_face_encoding = face_recognition.face_encodings(image_name)
    if len(image_face_encoding) == 1:
        face_encoding = image_face_encoding[0]
        known_encodings_new.append(face_encoding)
        people_new.append(person_name)

    else:
        print("NOTE: {} has more than one face.".format(image_file_name))

known_encodings_save = np.array(known_encodings_new)
people_save = np.array(people_new)

#Print the new people added for debugging( CAUTION: Disable for large cases)
# print("people = {} and {}".format(people_save, type(people_save)))
fileList = os.listdir(os.path.join(currentPath, filepath));

# Get a reference to the Raspberry Pi camera.
camera = picamera.PiCamera()
camera.resolution = (320, 240)
output = np.empty((240, 320, 3), dtype=np.uint8)

imageFiles = []
knownFaces = []
userIds = []

print("Fetching all the images that are used to recognize persons")

# Load all images and add them to the imageFiles array
for image in fileList:
    imageFiles.append(face_recognition.load_image_file(filepath + image))

    # Build the userIds to use later to find the correct user id based on the face recognition
    # Only supports one integer as userId
    if image.find("#") != -1:
        userIds.append(image.split("#")[1][:1])
    else:
        userIds.append("Unknown user id")

print("Encoding the images that were found")

# Get all the encodings of the images we found and add them to knownFaces array
for image in imageFiles:
    # But since I know each image only has one face, I only care about the first encoding in each image, so I grab index 0.
    knownFaces.append(face_recognition.face_encodings(image)[0])
    #Loading the image
    img = Image.open(image)
    s = os.path.splitext(image)
    s = os.path.split(s[0])
    file_img = s[1]
    source_image = image

    #80% into training, 20% into validation set
    if (i % 10 < 8):
        target_image = target_path + "/" + target[0] + "/" + file_img
    else:
        target_image = target_path + "/" + target[1] + "/" + file_img

    #get face landmark based on face_reconition
    face_image_np = face_recognition.load_image_file(source_image)
    face_locations = face_recognition.face_locations(face_image_np,
                                                     model="hog")
    face_landmarks = face_recognition.face_landmarks(face_image_np,
                                                     face_locations)

    #crop the image
    face_landmark = face_landmarks[0]
    crop_pixels = get_crop_pixs(face_landmark)
    cropped_img = img.crop(crop_pixels)

    #save the cropped iamge into (256,256)
    resize_image = cropped_img.resize((256, 256))
    target_image_origin = target_image + ".png"
    resize_image.save(target_image_origin, "PNG", quality=95)
import face_recognition
import glob

known_faces_encodings = dict()
test_image_encodings = []
quantity_faces = []

for i in glob.glob(
        "/home/alexandr/PycharmProjects/chatbot/base_of_photos/*.jpg"):
    photo = face_recognition.load_image_file(i)
    #print(face_recognition.face_encodings(photo))
    if not face_recognition.face_encodings(photo) == []:
        known_faces_encodings[i] = face_recognition.face_encodings(photo)[0]

for i in glob.glob("/home/alexandr/PycharmProjects/chatbot/photos/*.jpg"):
    test_image = face_recognition.load_image_file(i)
    test_image_locations = face_recognition.face_locations(test_image)
    #print(test_image_encodings)
    if not test_image_locations == []:
        test_image_encoding = face_recognition.face_encodings(
            test_image, test_image_locations)[0]
        test_image_encodings.append(test_image_encoding)
        quantity_faces.append(test_image_locations)
from PIL import Image
import face_recognition

# Load the jpg file into a numpy array
image = face_recognition.load_image_file("biden.jpg")

# Find all the faces in the image
face_locations = face_recognition.face_locations(image)

print("I found {} face(s) in this photograph.".format(len(face_locations)))

for face_location in face_locations:

    # Print the location of each face in this image
    top, right, bottom, left = face_location
    print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))

    # You can access the actual face itself like this:
    face_image = image[top:bottom, left:right]
    pil_image = Image.fromarray(face_image)
    pil_image.show()
Example #60
0
KNOWN_FACES_DIR = "known_faces"
UNKNOWN_FACES_DIR = "unknown_faces"
TOLERANCE = 0.6
FRAME_THICKNESS = 3
FONT_THICKNESS = 2

MODEL = "cnn"

print("loading known faces")

known_faces = []
known_names = []

for name in os.listdir(KNOWN_FACES_DIR):
    for filename in os.listdir(f"{KNOWN_FACES_DIR}/{name}"):
        image = face_recognition.load_image_file(
            f"{KNOWN_FACES_DIR}/{name}/{filename}")
        encoding = face_recognition.face_encodings(image)
        known_faces.append(encoding)
        known_names.append(name)

print("processing unknown faces")
for filename in os.listdir(UNKNOWN_FACES_DIR):
    print(filename)
    image = face_recognition.load_image_file(f"{UNKNOWN_FACES_DIR}/{filename}")
    loacations = face_recognition.face_locations(image, model=MODEL)
    encodings = face_recognition.face_encodings(image, loacations)
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

    for face_encoding, face_location in zip(encodings, loacations):
        results = face_recognition.compare_faces(known_faces[0], face_encoding,
                                                 TOLERANCE)