这段代码有一些缺陷和漏洞,首先来看几个重要的问题:
1. **某些变量初始化为空:**
- `images = []`
- `filenames = []`
- `all_face_locations = []`
- `all_face_encodings = []`
2. **缺少变量赋值或错误使用:**
- `label = labels` 应改为 `label = labels[i]`
3. **`face_recognition` 库的依赖问题:**
- 确保已经安装 `face_recognition` 库,可以用 `pip install face_recognition`。
以下是修正后的代码示例:
- import os
- import numpy as np
- from sklearn.cluster import DBSCAN
- import face_recognition
- def load_images_from_folder(folder):
- """
- 从指定文件夹加载所有图片。
- """
- images = []
- filenames = []
- for filename in os.listdir(folder):
- img = face_recognition.load_image_file(os.path.join(folder, filename))
- if img is not None:
- images.append(img)
- filenames.append(filename)
- return images, filenames
- def detect_faces_and_extract_encodings(images):
- """
- 对每张图片进行人脸检测,并提取每个人脸的特征向量。
- """
- all_face_locations = []
- all_face_encodings = []
- for image in images:
- # 检测人脸
- face_locations = face_recognition.face_locations(image)
- # 提取人脸特征
- face_encodings = face_recognition.face_encodings(image, face_locations)
- all_face_locations.append(face_locations)
- all_face_encodings.extend(face_encodings) # 将 list of list 展平成一个 list
- return all_face_locations, all_face_encodings
- def cluster_faces(face_encodings):
- """
- 使用DBSCAN算法对人脸特征向量进行聚类。
- """
- # 使用DBSCAN进行聚类
- clustering = DBSCAN(eps=0.5, min_samples=1).fit(face_encodings)
- return clustering.labels_
- def create_and_move_files(filenames, labels, folder_path):
- """
- 根据聚类标签创建文件夹,并将图片移动到相应的文件夹中。
- """
- # 获取所有标签的唯一值
- unique_labels = set(labels)
-
- # 对每个标签创建一个文件夹
- for label in unique_labels:
- new_folder = f"Person_{label}"
- os.makedirs(os.path.join(folder_path, new_folder), exist_ok=True)
-
- # 移动文件到相应的文件夹
- for i, filename in enumerate(filenames):
- label = labels[i]
- new_folder = f"Person_{label}"
- old_path = os.path.join(folder_path, filename)
- new_path = os.path.join(folder_path, new_folder, filename)
- os.rename(old_path, new_path)
- def organize_faces_by_person(folder_path):
- """
- 整个人脸组织流程的主函数。
- """
- # 加载图片
- images, filenames = load_images_from_folder(folder_path)
-
- # 检测所有人脸并提取特征
- all_face_locations, all_face_encodings = detect_faces_and_extract_encodings(images)
-
- # 聚类人脸
- labels = cluster_faces(all_face_encodings)
-
- # 创建文件夹并移动文件
- create_and_move_files(filenames, labels, folder_path)
- folder_path = 'path_to_your_images_folder' # 替换为你的图片文件夹路径
- organize_faces_by_person(folder_path)
复制代码
### 额外提示:
- **eps 参数调整**:调整 `DBSCAN` 的 `eps` 参数,根据实际效果来优化识别准确度。
- **调整图像大小**:如果图片特别大,可以考虑调整大小以加速处理。
希望这些改动能帮助你整理和分类本地 PC 上的照片。祝你成功!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。