通过face_recognition功能将文件夹下面的图片,以图片名为名字进行储存
然后读取新图片与现有文件夹下面的照片进行对比,达到识别人脸人名的目标
face_recognition 使用说明
https://github.com/ageitgey/face_recognition/blob/master/README_Simplified_Chinese.md
import face_recognition
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import cv2
import os
# This is an example of running face recognition on a single image
# and drawing a box around each person that was identified.
# 自动从sampe_images文件夹加载所有图片
known_face_encodings = []
known_face_names = []
images_path = "sampe_images"
# 遍历文件夹中的所有图片
for image_file in os.listdir(images_path):
try:
# 跳过非图片文件
if not image_file.lower().endswith(('.png', '.jpg', '.jpeg')):
continue
# 加载图片并获取人脸编码
image_path = os.path.join(images_path, image_file)
face_image = face_recognition.load_image_file(image_path)
face_encoding = face_recognition.face_encodings(face_image)
# 确保检测到了人脸
if len(face_encoding) > 0:
known_face_encodings.append(face_encoding[0])
# 使用文件名(不包含扩展名)作为人名
name = os.path.splitext(image_file)[0]
# 确保中文名称可以正确显示
try:
name = name.encode('utf-8').decode('utf-8')
except UnicodeError:
name = name.encode('gbk').decode('utf-8')
known_face_names.append(name)
print(f"成功加载图片: {name}")
except Exception as e:
print(f"处理图片 {image_file} 时出错: {str(e)}")
continue
# Load an image with an unknown face
unknown_image = face_recognition.load_image_file("f:/ldh.png")
# Find all the faces and face encodings in the unknown image
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)
# Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library
# See http://pillow.readthedocs.io/ for more about PIL/Pillow
pil_image = Image.fromarray(unknown_image)
# Create a Pillow ImageDraw Draw instance to draw with
draw = ImageDraw.Draw(pil_image)
# Loop through each face found in the unknown image
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# See if the face is a match for the known face(s)
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# Or instead, use the known face with the smallest distance to the new face
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
# 使用OpenCV绘制人脸框
cv2.rectangle(unknown_image, (left, top), (right, bottom), (0, 0, 255), 2)
# 使用PIL绘制中文文本
img_pil = Image.fromarray(unknown_image)
draw = ImageDraw.Draw(img_pil)
# 加载中文字体(请确保系统中有这个字体,或者使用其他可用的中文字体)
try:
font = ImageFont.truetype("simhei.ttf", 20) # 使用黑体
except:
try:
font = ImageFont.truetype("simsun.ttc", 20) # 尝试使用宋体
except:
font = ImageFont.load_default() # 如果都没有,使用默认字体
# 绘制文本背景
text_bbox = draw.textbbox((left, bottom + 5), name, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
draw.rectangle(((left, bottom), (left + text_width, bottom + text_height + 10)),
fill=(0, 0, 255))
# 绘制文本
draw.text((left, bottom + 5), name, font=font, fill=(255, 255, 255))
# 转换回OpenCV格式
unknown_image = np.array(img_pil)
# 创建窗口并显示结果
image_height, image_width = unknown_image.shape[:2]
window_title = "人脸识别结果".encode('gbk').decode(encoding='gbk')
cv2.namedWindow(window_title, cv2.WINDOW_NORMAL)
cv2.resizeWindow(window_title, image_width, image_height)
cv2.imshow(window_title, cv2.cvtColor(unknown_image, cv2.COLOR_RGB2BGR))
cv2.waitKey(0)
cv2.destroyAllWindows()
# You can also save a copy of the new image to disk if you want by uncommenting this line
# pil_image.save("image_with_boxes.jpg")