Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closes Program #1614

Open
TiagoCrippa opened this issue Oct 31, 2024 · 3 comments
Open

Closes Program #1614

TiagoCrippa opened this issue Oct 31, 2024 · 3 comments

Comments

@TiagoCrippa
Copy link

  • face_recognition version:
  • Python version: 3.12.6
  • Operating System: windows 11

Description

The package terminates my program every time it recognizes a face and the following error appears:

erro error

Code

import cv2
import face_recognition

video_capture = cv2.VideoCapture(0)

exemplo_imagem = face_recognition.load_image_file("exemplo.jpg")
exemplo_face_encodings = face_recognition.face_encodings(exemplo_imagem)

if len(exemplo_face_encodings) > 0:
exemplo_face_encoding = exemplo_face_encodings[0]
else:
print("Nenhum rosto encontrado na imagem de exemplo.")
video_capture.release()
cv2.destroyAllWindows()
exit()

conhecidos_face_encodings = [exemplo_face_encoding]
conhecidos_nomes = ["Exemplo"]

while True:
ret, frame = video_capture.read()
if not ret:
print("Não foi possível capturar o quadro.")
break

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(conhecidos_face_encodings, face_encoding)
    name = "Desconhecido"

    if True in matches:
        first_match_index = matches.index(True)
        name = conhecidos_nomes[first_match_index]

    cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
    cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

cv2.imshow('Video', frame)

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

video_capture.release()
cv2.destroyAllWindows()

@FeatureSpitter
Copy link

I have the same issue with their example: https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_from_webcam.py

$ python facerec_from_webcam_faster.py
Traceback (most recent call last):
  File "/home/milhas/projectos/airport/face_recognition/examples/facerec_from_webcam_faster.py", line 55, in <module>
    face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
  File "/home/milhas/.local/lib/python3.10/site-packages/face_recognition/api.py", line 214, in face_encodings
    return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks]
  File "/home/milhas/.local/lib/python3.10/site-packages/face_recognition/api.py", line 214, in <listcomp>
    return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks]
TypeError: compute_face_descriptor(): incompatible function arguments. The following argument types are supported:
    1. (self: _dlib_pybind11.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),numpy.uint8], face: _dlib_pybind11.full_object_detection, num_jitters: int = 0, padding: float = 0.25) -> _dlib_pybind11.vector
    2. (self: _dlib_pybind11.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),numpy.uint8], num_jitters: int = 0) -> _dlib_pybind11.vector
    3. (self: _dlib_pybind11.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),numpy.uint8], faces: _dlib_pybind11.full_object_detections, num_jitters: int = 0, padding: float = 0.25) -> _dlib_pybind11.vectors
    4. (self: _dlib_pybind11.face_recognition_model_v1, batch_img: list[numpy.ndarray[(rows,cols,3),numpy.uint8]], batch_faces: list[_dlib_pybind11.full_object_detections], num_jitters: int = 0, padding: float = 0.25) -> _dlib_pybind11.vectorss
    5. (self: _dlib_pybind11.face_recognition_model_v1, batch_img: list[numpy.ndarray[(rows,cols,3),numpy.uint8]], num_jitters: int = 0) -> _dlib_pybind11.vectors

Invoked with: <_dlib_pybind11.face_recognition_model_v1 object at 0x7533edf50bb0>, array([[[119, 126, 126],
        [129, 131, 132],
        [130, 130, 135],
        ...,
        [ 71,  76,  88],
        [ 70,  71,  84],
        [ 74,  72,  84]],

       [[126, 127, 133],
        [128, 128, 134],
        [130, 130, 136],
        ...,
        [ 71,  75,  90],
        [ 69,  72,  85],
        [ 76,  77,  88]],

       [[125, 124, 133],
        [126, 126, 136],
        [126, 129, 140],
        ...,
        [ 71,  74,  88],
        [ 70,  75,  86],
        [ 71,  75,  87]],

       ...,

       [[ 82,  73,  52],
        [ 79,  71,  52],
        [ 79,  72,  52],
        ...,
        [ 64,  68,  76],
        [ 65,  68,  75],
        [ 64,  68,  72]],

       [[ 79,  71,  50],
        [ 71,  63,  43],
        [ 66,  55,  36],
        ...,
        [ 64,  66,  73],
        [ 63,  67,  72],
        [ 63,  67,  72]],

       [[ 51,  42,  25],
        [ 42,  32,  17],
        [ 49,  37,  25],
        ...,
        [ 66,  67,  74],
        [ 61,  65,  72],
        [ 61,  64,  72]]], dtype=uint8), <_dlib_pybind11.full_object_detection object at 0x7533ef7f7030>, 1

@JoelPC1000
Copy link

For me, it would just no error, while looking for solutions I found this that worked:
replace the code line, rgb_frame = frame[:, :, ::-1]
with below code line, rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
I'm
Windows: 11
Using
python: 3.12.7

@Tanishq-JM
Copy link

Exception has occurred:

TypeError
compute_face_descriptor(): incompatible function arguments. The following argument types are supported:
  (self: _dlib_pybind11.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),numpy.uint8], face: _dlib_pybind11.full_object_detection, num_jitters: int = 0, padding: float = 0.25) -> _dlib_pybind11.vector
  (self: _dlib_pybind11.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),numpy.uint8], num_jitters: int = 0) -> _dlib_pybind11.vector
   (self: _dlib_pybind11.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),numpy.uint8], faces: _dlib_pybind11.full_object_detections, num_jitters: int = 0, padding: float = 0.25) -> _dlib_pybind11.vectors
   (self: _dlib_pybind11.face_recognition_model_v1, batch_img: List[numpy.ndarray[(rows,cols,3),numpy.uint8]], batch_faces: List[_dlib_pybind11.full_object_detections], num_jitters: int = 0, padding: float = 0.25) -> _dlib_pybind11.vectorss
   (self: _dlib_pybind11.face_recognition_model_v1, batch_img: List[numpy.ndarray[(rows,cols,3),numpy.uint8]], num_jitters: int = 0) -> _dlib_pybind11.vectors

python code

    import face_recognition
import os
import sys
import cv2
import numpy as np
import math
from datetime import datetime

# Function to calculate face confidence
def face_confidence(face_distance, face_match_threshold=0.6):
    range_ = 1.0 - face_match_threshold
    linear_val = (1.0 - face_distance) / (range_ * 2.0)
    if face_distance > face_match_threshold:
        return f"{round(linear_val * 100, 2)}%"
    else:
        val = (linear_val + ((1.0 - linear_val) * math.pow((linear_val - 0.5) * 2, 0.2))) * 100
        return f"{round(val, 2)}%"

# Face Recognition class
class FR:
    def __init__(self):
        self.face_locations = []
        self.face_encodings = []
        self.face_name = []
        self.known_face_encodings = []
        self.known_face_name = []
        self.process_current_frame = True
        self.Time = datetime.now()

        # Logging setup
        self.text_file = open("D:\\python\\sec_c.txt", 'a')
        self.text_file.write("***********************Activated by command mode***********************\n")
        
        self.encode_faces()

    # Encode known faces from the 'faces' folder
    def encode_faces(self):
        for image in os.listdir("faces"):
            face_image = face_recognition.load_image_file(f"faces/{image}")
            # Check if face encoding is found
            encodings = face_recognition.face_encodings(face_image)
            if encodings:
                self.known_face_encodings.append(encodings[0])
                self.known_face_name.append(image)
            else:
                print(f"Could not find any face encoding for {image}")

    # Run real-time face recognition
    def run_recongnition(self):
        video_capture = cv2.VideoCapture(0)
        if not video_capture.isOpened():
            sys.exit("Video source not found.")
        
        detected_names = set()

        while True:
            ret, frame = video_capture.read()
            if not ret:
                print("Failed to grab frame.")
                break

            if self.process_current_frame:
                # Resize frame for faster processing
                small_image = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
                rgb_small_image = small_image[:, :, ::-1]

                # Detect face locations
                self.face_locations = face_recognition.face_locations(rgb_small_image)
                if not self.face_locations:
                    continue
                # Encode faces
                try:
                    self.face_encodings = face_recognition.face_encodings(rgb_small_image, self.face_locations)
                    print(self.face_locations);break
                    if not self.face_encodings:
                        print("No face encodings generated! Skipping...")
                        continue
                except Exception as e:
                    print(f"Error during face encoding: {e}")
                    self.face_encodings = []
                    continue

                self.face_name = []

                for face_encoding in self.face_encodings:
                    matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding)
                    name = "Unknown"
                    confidence = "???" 

                    if matches:
                        face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)
                        best_match_index = np.argmin(face_distances)

                        if matches[best_match_index]:
                            name = self.known_face_name[best_match_index]
                            confidence = face_confidence(face_distances[best_match_index])

                            if float(confidence.rstrip("%")) > 94:
                                name = name.rstrip(".jpg")
                                detected_names.add(name)
                                self.face_name.append(f"{name}({confidence})")

            self.process_current_frame = not self.process_current_frame

            # Draw rectangles and labels around detected faces
            for (top, right, bottom, left), name in zip(self.face_locations, self.face_name):
                top *= 4
                right *= 4
                bottom *= 4
                left *= 4
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), -1)
                cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 1)

            cv2.imshow("Face Recognition", frame)

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

        video_capture.release()
        cv2.destroyAllWindows()
        return detected_names

# Function to initialize and run face recognition
def Facein():
    fr = FR()
    detected_faces = fr.run_recongnition()
    return detected_faces

# Run the face recognition
Facein()

please help me make it work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants