识别人脸人名,只是窗口的中文乱码待解决

通过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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

养牛大人

感谢您的鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值