anisayari/easy_facial_recognition

bug d'indentation

Opened this issue · 5 comments

bonjour monsieur Anis
j'ai essayé votre code publié sur github mais j'ai toujours un erreur de path !! :(
peut etre que l'emplacement des images du dossier ou se trouve la liste know_face n'est pas indenté??
`voila le code

import cv2
import dlib
import PIL.Image
import numpy as np
from imutils import face_utils
from pathlib import Path
import os
import ntpath

print('[INFO] Starting System...')
print('[INFO] Importing pretrained model..')
pose_predictor_68_point = dlib.shape_predictor("D:/python/IOT/pretrained_model/shape_predictor_68_face_landmarks.dat")
pose_predictor_5_point = dlib.shape_predictor("D:/python/IOT/pretrained_model/shape_predictor_5_face_landmarks.dat")
face_encoder = dlib.face_recognition_model_v1("D:/python/IOT/pretrained_model/dlib_face_recognition_resnet_model_v1.dat")
face_detector = dlib.get_frontal_face_detector()
print('[INFO] Importing pretrained model..')

def transform(image, face_locations):
coord_faces = []
for face in face_locations:
rect = face.top(), face.right(), face.bottom(), face.left()
coord_face = max(rect[0], 0), min(rect[1], image.shape[1]), min(rect[2], image.shape[0]), max(rect[3], 0)
coord_faces.append(coord_face)
return coord_faces

def encode_face(image):
face_locations = face_detector(image, 1)
face_encodings_list = []
landmarks_list = []
for face_location in face_locations:
# DETECT FACES
shape = pose_predictor_68_point(image, face_location)
face_encodings_list.append(np.array(face_encoder.compute_face_descriptor(image, shape, num_jitters=1)))
# GET LANDMARKS
shape = face_utils.shape_to_np(shape)
landmarks_list.append(shape)
face_locations = transform(image, face_locations)
return face_encodings_list, face_locations, landmarks_list

def easy_face_reco(frame, known_face_encodings, known_face_names):
rgb_small_frame = frame[:, :, ::-1]
# ENCODING FACE
face_encodings_list, face_locations_list, landmarks_list = encode_face(rgb_small_frame)
face_names = []
for face_encoding in face_encodings_list:
if len(face_encoding) == 0:
return np.empty((0))
# CHECK DISTANCE BETWEEN KNOWN FACES AND FACES DETECTED
vectors = np.linalg.norm(known_face_encodings - face_encoding, axis=1)
tolerance = 0.6
result = []
for vector in vectors:
if vector <= tolerance:
result.append(True)
else:
result.append(False)
if True in result:
first_match_index = result.index(True)
name = known_face_names[first_match_index]
else:
name = "Unknown"
face_names.append(name)

for (top, right, bottom, left), name in zip(face_locations_list, face_names):
    cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
    cv2.rectangle(frame, (left, bottom - 30), (right, bottom), (0, 255, 0), cv2.FILLED)
    cv2.putText(frame, name, (left + 2, bottom - 2), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 1)

for shape in landmarks_list:
    for (x, y) in shape:
        cv2.circle(frame, (x, y), 1, (255, 0, 255), -1)

if name == 'main':

print('[INFO] Importing faces...')

face_to_encode_path = ['D:/python/chaima1/known_face/Zuckerberg.png','D:/python/chaima1/known_face/chaima.jpg']

known_face_encodings = []

for face_to_encode_path in face_to_encode_path:
    
    image = PIL.Image.open(face_to_encode_path)
    image = np.array(image)
    face_encoded = encode_face(image)[0][0]
    known_face_encodings.append(face_encoded)
    known_face_names = ["Chaima",'Zuckerberg']

print('[INFO] Faces well imported')
print('[INFO] Starting Webcam...')
video_capture = cv2.VideoCapture(0)
print('[INFO] Webcam well started')
print('[INFO] Detecting...')
while True:
    ret, frame = video_capture.read()
    easy_face_reco(frame, known_face_encodings, known_face_names)
    cv2.imshow('Easy Facial Recognition App', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
print('[INFO] Stopping System')
video_capture.release()
cv2.destroyAllWindows()

voila l'erreur
File "D:\python\chaima1\chaima.py", line 89
for face_to_encode_path in face_to_encode_path:
^
IndentationError: unexpected indent
`

Impossible de lire le code dans ce format.

Concernant l'indentation de la liste des visages connus elle est correctement indenté dans le repo :

known_face_names = [os.path.splitext(ntpath.basename(file_))[0] for file_ in files]

L'indentation est une base de python : https://www.w3schools.com/python/gloss_python_indentation.asp#:~:text=Indentation%20refers%20to%20the%20spaces,indicate%20a%20block%20of%20code.

Concernant cette erreur :
File "D:\python\chaima1\chaima.py", line 89 for face_to_encode_path in face_to_encode_path: ^ IndentationError: unexpected indent

Elle n'a rien a voir avec le chemin de fichier, mais bien une erreur d'indentation dans ton code.

Aussi, je t'invite à lire ici comment ouvrir une issue correctement sur un repo github https://medium.com/nyc-planning-digital/writing-a-proper-github-issue-97427d62a20f#:~:text=When%20you%20click%20%E2%80%9CNew%20issue,you%20write%20a%20proper%20issue.

Et je t'invite aussi à utilisé correctement la syntaxe markdown : https://guides.github.com/features/mastering-markdown/

merciii infiniment monsieur pour votre interaction je vais essayer votre solution à travers ces liens que trouve trés utiles pour résoudre et comprendre le code et je laisserai un commentaire si ca marche

@anisayari @chaim-dev je rencontre une erreur de ce type mais l'origine est différente.
os x 10.13
conda env
python3.6
(j'ai pas d'issues similaire en utilisant YoLo ou DarkNet par exemple)

python3 easy_facial_recognition.py --i known_faces
[INFO] Starting System...
[INFO] Importing pretrained model..
[INFO] Importing pretrained model..
[INFO] Importing faces...
Traceback (most recent call last):
File "easy_facial_recognition.py", line 93, in
known_face_names = [os.path.splitext(ntpath.basename(file_))[0] for file_ in files]
...
...
...
/Users/sofiane/opt/lib/python3.5/ntpath.py", line 139, in splitdrive
if len(p) >= 2:
TypeError: object of type 'PosixPath' has no len()

///////// What I do>
J'ai ajouter à la ligne 89 *jpg ce qui donne cela :

python3 easy_facial_recognition.py --i known_faces
[INFO] Starting System...
[INFO] Importing pretrained model..
[INFO] Importing pretrained model..
[INFO] Importing faces...
Traceback (most recent call last):
File "easy_facial_recognition.py", line 92, in
raise ValueError('No faces detect in the directory: {}'.format(face_to_encode_path))
ValueError: No faces detect in the directory: known_faces

@anisayari
Im here now with script after fews setting (but why it dont detect faces?)

[INFO] Starting System...
[INFO] Importing pretrained model..
[INFO] Importing pretrained model..
[INFO] Importing faces...
Traceback (most recent call last):
File "easy_facial_recognition.py", line 92, in
raise ValueError('No faces detect in the directory: {}'.format(face_to_encode_path))
ValueError: No faces detect in the directory: /known_faces

bonjour @anisayari
voici le code pour me le corriger :

# Code Anis - Defend Intelligence
import cv2
import dlib
import PIL.Image
import numpy as np
from imutils import face_utils
import argparse
from pathlib import Path
import os
import ntpath


print('[INFO] Starting System...')
print('[INFO] Importing pretrained model..')
pose_predictor_68_point = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
pose_predictor_5_point = dlib.shape_predictor("shape_predictor_5_face_landmarks.dat")
face_encoder = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")
face_detector = dlib.get_frontal_face_detector()
print('[INFO] Importing pretrained model..')


def transform(image, face_locations):
    coord_faces = []
    for face in face_locations:
        rect = face.top(), face.right(), face.bottom(), face.left()
        coord_face = max(rect[0], 0), min(rect[1], image.shape[1]), min(rect[2], image.shape[0]), max(rect[3], 0)
        coord_faces.append(coord_face)
    return coord_faces


def encode_face(image):
    face_locations = face_detector(image, 1)
    face_encodings_list = []
    landmarks_list = []
    for face_location in face_locations:
        # DETECT FACES
        shape = pose_predictor_68_point(image, face_location)
        face_encodings_list.append(np.array(face_encoder.compute_face_descriptor(image, shape, num_jitters=1)))
        # GET LANDMARKS
        shape = face_utils.shape_to_np(shape)
        landmarks_list.append(shape)
    face_locations = transform(image, face_locations)
    return face_encodings_list, face_locations, landmarks_list


def easy_face_reco(frame, known_face_encodings, known_face_names):
    rgb_small_frame = frame[:, :, ::-1]
    # ENCODING FACE
    face_encodings_list, face_locations_list, landmarks_list = encode_face(rgb_small_frame)
    face_names = []
    for face_encoding in face_encodings_list:
        if len(face_encoding) == 0:
            return np.empty((0))
        # CHECK DISTANCE BETWEEN KNOWN FACES AND FACES DETECTED
        vectors = np.linalg.norm(known_face_encodings - face_encoding, axis=1)
        tolerance = 0.6
        result = []
        for vector in vectors:
            if vector <= tolerance:
                result.append(True)
            else:
                result.append(False)
        if True in result:
            first_match_index = result.index(True)
            name = known_face_names[first_match_index]
        else:
            name = "Unknown"
        face_names.append(name)

    for (top, right, bottom, left), name in zip(face_locations_list, face_names):
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
        cv2.rectangle(frame, (left, bottom - 30), (right, bottom), (0, 255, 0), cv2.FILLED)
        cv2.putText(frame, name, (left + 2, bottom - 2), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 1)

    for shape in landmarks_list:
        for (x, y) in shape:
            cv2.circle(frame, (x, y), 1, (255, 0, 255), -1)


if __name__ == '__main__':
    args = parser.parse_args()

    print('[INFO] Importing faces...')
    face_to_encode_path = ["known_faces"]
    files = [file_ for file_ in face_to_encode_path.rglob('*.jpg')]

    for file_ in face_to_encode_path.rglob('*.png'):
        files.append(file_)
    if len(files)==0:
        raise ValueError('No faces detect in the directory: {}'.format(face_to_encode_path))
    known_face_names = [os.path.splitext(ntpath.basename(file_))[0] for file_ in files]

    known_face_encodings = []
    for file_ in files:
        image = PIL.Image.open(file_)
        image = np.array(image)
        face_encoded = encode_face(image)[0][0]
        known_face_encodings.append(face_encoded)

    print('[INFO] Faces well imported')
    print('[INFO] Starting Webcam...')
    video_capture = cv2.VideoCapture(0)
    print('[INFO] Webcam well started')
    print('[INFO] Detecting...')
    while True:
        ret, frame = video_capture.read()
        easy_face_reco(frame, known_face_encodings, known_face_names)
        cv2.imshow('Easy Facial Recognition App', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    print('[INFO] Stopping System')
    video_capture.release()
    cv2.destroyAllWindows()

bon l'erreur est :

Traceback (most recent call last):
File "C:\Users\ziani_x0au9tx\Desktop\easy_facial_recognition-master\easy_facial_recognition.py", line 17, in
pose_predictor_68_point = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
RuntimeError: Unable to open shape_predictor_68_face_landmarks.dat

j'ai essayer de chaner la place des *.dat en modifiant aussi le code en dépandant mais le problème est toujours présent

q'est ce que je peux faire pour ça ?