From 7422b25bf6457ffda2eec92256b1adf04c4f224e Mon Sep 17 00:00:00 2001 From: "Antonio J. Delgado" Date: Wed, 8 Sep 2021 14:36:28 +0300 Subject: [PATCH] Add check for image files --- image_classifier/image_classifier.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/image_classifier/image_classifier.py b/image_classifier/image_classifier.py index bb1b302..ad1b3bf 100755 --- a/image_classifier/image_classifier.py +++ b/image_classifier/image_classifier.py @@ -148,7 +148,7 @@ class image_classifier: if os.access(self.faces_directory, os.R_OK): with os.scandir(self.faces_directory) as faces_items: for entry in faces_items: - if not entry.name.startswith('.') and entry.is_file(): + if not entry.name.startswith('.') and entry.is_file() and self.is_image(self.faces_directory + os.sep + entry.name): self._log.debug(f"Identifying face in file '{entry.name}'...") person = dict() person['filename'] = face_recognition.load_image_file(self.faces_directory + os.sep + entry.name) @@ -164,7 +164,7 @@ class image_classifier: def find_faces(self, file): ''' Find faces in an image/video file ''' people = list() - try: + if self.is_image(file): image = face_recognition.load_image_file(file) encodings = face_recognition.face_encodings(image) self._log.debug(f"Found {len(encodings)} faces.") @@ -173,11 +173,18 @@ class image_classifier: if face_recognition.compare_faces([known_person['encoding']], encoding)[0]: if known_person['name'] not in people: people.append(known_person['name']) - except PIL.UnidentifiedImageError as error: - self._log.debug(f"File '{file}' don't seem to be an image.") + else: return False return people + def is_image(self, file): + try: + im = PIL.Image.open(file) + except PIL.UnidentifiedImageError as error: + self._log.debug(f"File '{file}' is not an image recognizable by PIL. {error}") + return False + return True + def _init_log(self): ''' Initialize log object ''' self._log = logging.getLogger("image_classifier")