How can I fix the following error:
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 all the files in the KNOWN_FACES
directory. In your specific case also the .DS_Store
file.
You can filter the results considering only directories and excluding files such as .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)