Face Recognition With Raspberry Pi and OpenCV

Thanks for the reply.
I’m really good to detect one person, but I’d like to detect several people from my family (3).
And here I’m stuck.
Building one directory for each person is fine.
In model_training:
imagePaths = list(paths.list_images(“dataset/henri”))
And then ?
Building a second and third directory for another person is fine.
But how do I tell “model_training” ?
Will “model_training” scan all directories on its own ?
And inside “facial_recognition.py”: known_face_names = data[“henri”,“other_1”,“other_2”]
Thanks again for your interest.

2 Likes

Hey @Henri296003,

The model_training.py script should check the ‘dataset’ directory and train the model with each individual subfolder you have added here.

Inside of model_training.py, the line imagePaths = list(paths.list_images("dataset")) will create a list of all the subdirectories inside of dataset.

Then the for loop in this code, for (i, imagePath) in enumerate(imagePaths):, will repeat the training process for each face you have added to ‘dataset’ and pass on this model set to facial_recognition.py.

Just make sure you:

  • Create folders containing photos of the faces you wish to detect using image_capture.py
  • Then run model_training.py
  • Then run facial_recognition.py

Hope this helps! :slight_smile:

2 Likes

Okay! I’m really new to this.
There’s progress.
I’m detecting two faces (and I only have two! It’s stupid, I’m waiting for guests to play along).
It’s just for my own personal development.
Thanks, Samuel.

1 Like

Hello, this is a great start for me in Python, so thank you!
I am able to get the facial recognition to work and it identifies me, shows my name but does not execute a function. I have been trying to get it to do a Servo action upon seeing me but have been unsuccessful. I had also tried to do a simple text output as well but that has not worked either. The Servo motor function does work as a separate script on the Pi5 16GB, so there is action possible. Any suggestion on what I am not doing would be great!

facial_recognition_hardware_Latest-05-30-25.py.zip (2.1 KB)

Hi @Chris296185

Looking at your code the “process_frame()” function you have returns the frame inside the face-encoding loop, so it is exiting before the servos can move.

If you replace the process_frame function you have with the below code (the authorized face detected if statement has had its indent removed) it should work for you.

def process_frame(frame):
    global face_locations, face_encodings, face_names

    resized_frame = cv2.resize(frame, (0, 0), fx=(1/cv_scaler), fy=(1/cv_scaler))
    rgb_resized_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB)

    face_locations = facial_recognition.face_locations(rgb_resized_frame)
    face_encodings = facial_recognition.face_encodings(rgb_resized_frame, face_locations, model='large')

    face_names = []
    authorized_face_detected = False

    for face_encoding in face_encodings:
        matches = facial_recognition.compare_faces(known_face_encodings, face_encoding)
        name = "Unknown"

        face_distances = facial_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]
            if name in authorized_names:
                authorized_face_detected = True

        face_names.append(name)

    # Control the GPIO pin based on face detection (moved out of the loop)
    if authorized_face_detected:
        print("HI Chris!!!")
        servo.mid()
        print("mid")
        sleep(2)
        servo.min()
        print("min")
        sleep(2)
        servo.mid()
        print("mid")
        sleep(2)
        servo.max()
        print("max")
        sleep(2)

    return frame  # ← Now placed AFTER the loop, as it should be
1 Like

ValueError: numpy.dtype size changed, may indicate binary incompatibility.
Expected 96 from C header, got 88 from PyObject
can someone help with this please? i get it when i start to run the image capture

2 Likes

Hey @Bright302385, welcome to the forums!

I suspect you have a NumPy version conflict here. Is this a fresh installation of PiOS? If you have installed NumPy before (practically any other computer vision tutorial will do this), then it might be conflicting with the one used in this guide.

If possible, a fresh installation of PiOS would fix this. Is this possible in your project?

Cheers!
-Jaryd

2 Likes

Hi Jaryd. I was trying to replicate this project again on another newly flashed card raspberrypi(Literally flashed today). But after following the guide I had the same error: ValueError: numpy.dtype size changed, may indicate binary incompatibility.
Expected 96 from C header, got 88 from PyObject
Is there any chance any other cause could be making this error.

Thanks

Hey @Kelvin293406,

We might need to install a version of Numpy that satisfies everything. I think when we include site system packages it brings a much newer version of numpy and causes the conflict (but we need to include the system packages to use Picamera2)!

I’m just pulling this fix from another guide we have been working on with a similar issue. Open up the face_rec venv with:

source face_rec/bin/activate

Then manually install this specific version of Numpy:

pip3 install numpy==1.26.4


Let us know how that goes!

2 Likes

Hi Jaryd:

This was indeed the solution. Thank you.

2 Likes

Hi, new pi 5 user here, I get it at Xmas but looking to learn while I wait. I see that you set this up in a virtual environment, if I create my functions to work for my use case, how do you go from running it in virtual to running on boot of the pi 5?

This above is probably a very noob question but hey we all start somewhere right? Lol.

Thanks in advance

1 Like

Hi there, @Benjamin307041, and welcome to the forum. Glad to have you here.

Easy as Pi.

You just need to make a little bash script that will do three things: wait 20s or so (to let the entire system catch up and activate), boot into the Virtual Environment, run your Python script.

Then, put the script into the ~/config/autostart folder, make sure the computer has executable permissions, and reboot.

Some commands below:

sudo -i
vi startup.sh

Then, create the following file, changing the path names as required:

#!/bin/bash

#Sleeps for 30 seconds at boot just to give the entire system time to catch up.
sleep 30

#Activate the venv
source /path/to/your/venv/activate

#Begin the script.
python3 /path/to/your/script.py

Then make the script executeable via this command:

chmod 755 startup.sh

Then,

vi /etc/rc.local`

And at the following text before exit 0.

/root/startup.sh &

And reboot and everything should work.

P.S. I use vi a lot here, but you can use any text editor. My preference is Vim, but it needs to be installed first.

2 Likes

Thank you :slight_smile:

2 Likes