mp.jpeg
mp.jpeg

Reputation: 197

Python Face-Recognition - Search Folder of multiple images for match

I have the following code:

import face_recognition
from PIL import Image, ImageDraw
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from shutil import copyfile

#Ask user for file name
Tk().withdraw()
filename = askopenfilename()

#Add known images 
image_of_person = face_recognition.load_image_file(filename)
person_face_encoding = face_recognition.face_encodings(image_of_person)[0]

for i in range (1, 8):

    #Construct the picture name and print it
    file_name = str(i).zfill(5) + ".jpg"
    print(file_name)

    #Load the file
    newPic = face_recognition.load_image_file(file_name)

    #Search every detected face
    for face_encoding in face_recognition.face_encodings(newPic):


        results = face_recognition.compare_faces([person_face_encoding], face_encoding, 0.5)

        #If match, show it
        if results[0] == True:
            copyFile(file_name, "./img/saved" + file_name)

The intention is to use the known image (image_of_person) and search a folder of images ('./img/unknown') for a match, then show the matched photo.

I receive the error:

No such file or directory: '00001.jpg'

On the line

 newPic = face_recognition.load_image_file(file_name)

How do I point the recognition to the sample of images folder?

Note: for i in range (1, 8): - 8 Images are in the sample folder.

Upvotes: 3

Views: 2425

Answers (1)

Zionsof
Zionsof

Reputation: 1246

I think your problem is you're not giving the right path when trying to load the images.

Change

file_name = str(i).zfill(5) + ".jpg"

to

file_name = f"./img/unknown/{str(i).zfill(5)}.jpg"

Note: If you're using python2, then

  • file_name = "./img/unknown/{}.jpg".format(str(i).zfill(5)

Another tip, if you want your code to be generic, no matter how many images there are, you can do

  • for i in range(1, len(os.listdir("./img/unknown"))).

Or, even better, you can simply do

for img in os.listdir("img/unknown"):
    file_name = os.path.join("img/unknown", img)
    ... continue with the rest of the flow ...

Upvotes: 3

Related Questions