NotADirectoryError: [Errno 20] Not a directory: 'known_faces/.DS_Store'

NotADirectoryError: [Errno 20] Not a directory: 'known_faces/.DS_Store'

如何修复以下错误:

NotADirectoryError: [Errno 20] Not a directory: 'known_faces/.DS_Store'

代码

import face_recognition
import os
import cv2
import numpy as np

KNOWN_FACES = "known_faces"
UNKNOWN_FACES = "unknown_faces"
TOLERANCE = 0.6
THICKNESS = 3
MODEL = "cnn"

known_faces = []
known_names = []

for name in os.listdir(KNOWN_FACES):
    for filename in os.listdir(f"{KNOWN_FACES}/{name}"):

        image = face_recognition.load_image_file(f"{KNOWN_FACES}/{name}/{filename}")
        encoding = face_recognition.face_encodings(image)
        known_faces.append(encoding)
        known_names.append(name)

print("processing unknown_faces")
for filename in os.listdir(UNKNOWN_FACES):
    print(filename)

    image = face_recognition.load_image_file(f"{UNKNOWN_FACES}/{filename}")
    locations = face_recognition.face_locations(image, model=MODEL)
    encodings = face_recognition.face_encodings(image, locations)
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

    for face_encoding, face_locations in zip(encodings, locations):
        
        results = face_recognition.compare_faces(face_encoding, known_faces, TOLERANCE)
        MATCH = None
        if True in results:
            match = known_names[results.index(True)]
            print(f"Match found: {match}")

            top_left = (face_location[3], face_location[0])
            bot_right = (face_location[1], face_location[2])

            color = [0, 255, 0]

            cv2.rectangle(image, top_left, bot_right, color, THICKNESS)

            top_left = (face_location[3], face_location[0])
            bot_right = (face_location[1], face_location[2] + 22)
            cv2.rectangle(image, top_left, bot_right, color, cv2.FILLED)
            cv2.putText(image, math, (face_location[3]+10, face_location[2])+15, cv2.FONT_HERSEY_SIMPLEX, 0.5, (200,200,200), THICKNESS)

    cv2.imshow(filename, image)
    cv2.waitKey(10000)

os.listdir(KNOWN_FACES) returns KNOWN_FACES 目录下的所有文件。在您的具体情况下,还有 .DS_Store 文件。

您可以过滤结果只考虑目录并排除文件,例如 .DS_Store.

import os

for name in os.listdir(KNOWN_FACES):
    dir_path = os.path.join(KNOWN_FACES, name)
    # if it's a directory
    if os.path.isdir(dir_path):
       for filename in os.listdir(dir_path):
          # if the file is a valid file (a better way could be to check your specific extension, e.g., png)
          if not filename.startswith('.'): 
              filepath = os.path.join(dir_path, filename)
              image = face_recognition.load_image_file(filepath)

您的“known_faces”目录中有一个名为 .DS_Store 的文件。由于您只想查看“known_faces”目录中的目录,因此您需要删除该文件。

正如 abc 所指出的,您可能只想检查您是否正在使用 os.path.isdir().

查找目录