最近给我亲戚实现一个在windows下根据人脸识别找到所有类似照片的需求,通过python学了下,特别在windows下的环境搭建方面遇到了很多的坑,环境搭建可以查看前两篇博客有讲述安装中的坑,这里分享下通过python实现这个功能的代码
代码的实现并不是很难,其中主要用到的类库就是Face_Recognition,这个类库在mac、linux上可以完美适配,特别在windows上出现的问题很多,特别是Face_Recognition需要用到的dlib在windows上无法安装,以下的这个通过一张照片全局查找类似照片的代码,谢谢指正。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import face_recognition import os import shutil from glob import glob from PIL import Image as pil_image
class Find:
def find_start(self): print(f"处理完成后命中的图片会被复制到C盘下的[target]文件夹!") print(f"全盘扫描中,速度较慢,耐心等待!")
target_img = input(f"请输入目标图片绝对地址(例如:E:/download/z.jpg):") print(f"开始处理,请等待...") images_list = self.get_images_from_all_drives() print(f"总共扫描到" + str(len(images_list)) + "张有效图片")
reference_image = face_recognition.load_image_file(target_img) reference_face_images = face_recognition.face_locations(reference_image) reference_face_encodings = face_recognition.face_encodings(reference_image, reference_face_images)
target_images = [] for image_path in images_list: try: pil_image.open(image_path) image = face_recognition.load_image_file(image_path) location_images = face_recognition.face_locations(image) if len(location_images) <= 0 or len(location_images) > 5: print(".", end='') continue face_encodings = face_recognition.face_encodings(image, location_images) for face_encoding1 in reference_face_encodings: for face_encoding2 in face_encodings: match_score = face_recognition.face_distance([face_encoding1], face_encoding2) if match_score[0] <= 0.5: target_images.append(image_path) print(".", end='') else: print(".", end='') except pil_image.UnidentifiedImageError: continue
if len(target_images) > 0: destination_path = "C:\\target" self.create_folder_if_not_exists(destination_path) for img in target_images: shutil.copy2(img, destination_path) print(f"处理完成!")
@staticmethod def create_folder_if_not_exists(folder_name): if not os.path.exists(folder_name): os.makedirs(folder_name)
@staticmethod def get_images_from_all_drives(): images_list = [] drives = [f"{letter}:" for letter in 'CDEFGH' if os.path.exists(f"{letter}:\\")] for drive in drives: for pattern in ('*.jpg', '*.jpeg', '*.png'): images_list.extend(glob(f"{drive}\\**\\{pattern}", recursive=True)) return images_list
if __name__ == '__main__': find_class = Find() images = find_class.find_start()
|