Python 人脸识别 - 搜索文件夹中的多张图片进行匹配

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

我有以下代码:

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)

目的是使用已知图像 (image_of_person) 并在图像文件夹 ('./img/unknown') 中搜索匹配项,然后显示匹配的照片.

我收到错误:

No such file or directory: '00001.jpg'

在线

 newPic = face_recognition.load_image_file(file_name)

如何将识别指向images文件夹的样本?

注意:for i in range (1, 8): - 示例文件夹中有 8 张图像。

我认为你的问题是你在尝试加载图像时没有提供正确的路径。

改变

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

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

注意:如果您使用的是 python2,则

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

另外一个提示,如果你希望你的代码是通用的,不管图片有多少,你都可以做到

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

或者,更好的是,您可以简单地做

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