Python3.8 reconocimiento facial estático

Uno, instale bibliotecas dependientes

pip install dlib
pip install numpy
pip install face_recognition
pip install opencv-python

Segundo, prepara la imagen

1. Imágenes conocidas

2. Imagen desconocida

 Tres, escritura de código

import cv2                      #图像处理的库OpenCv
import face_recognition
from PIL import Image, ImageDraw
import numpy as np

#读取图片
qbs_image = face_recognition.load_image_file("qbs1.jpg") # 乔布斯
my_image = face_recognition.load_image_file("my1.jpg") # 马云
unknown_image = face_recognition.load_image_file("my2.jpg") # 未知照片
unknow_my_image = cv2.imread('my2.jpg')

#处理图片
qbs_face_encoding = face_recognition.face_encodings(qbs_image)[0]
my_face_encoding = face_recognition.face_encodings(my_image)[0]
unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]


known_face_encodings = [
 qbs_face_encoding,
 my_face_encoding
]

known_face_names = [
 "qbs",
 "my"
 ]

#人脸位置
face_locations = face_recognition.face_locations(unknown_image)
face_encodings = face_recognition.face_encodings(unknown_image, face_locations)
#读取图片
pil_image = Image.fromarray(unknown_image)
draw = ImageDraw.Draw(pil_image)

#画框框
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
    # print(str(top)+'**'+str(right)+'**'+str(bottom)+'**'+str(left))
    # print(face_locations)
    matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
    # print(matches)
    face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
    # print(face_distances)
    best_match_index = np.argmin(face_distances)#找到位置图片对应人物在列表的序号
    # print(best_match_index)
    if matches[best_match_index]:
        name = known_face_names[best_match_index]#匹配已知列表的名称
        draw.rectangle(((left, top), (right, bottom)), outline=(0, 255, 0))#rgb:绿色
        text_width, text_height = draw.textsize(name)
        # print(str(text_width)+'****'+str(text_height))
        draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255))
        draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255))
#删除内存图片
del draw
#图片显示和保存
pil_image.show()
pil_image.save("recognize.jpg")

results = face_recognition.compare_faces(known_face_encodings, unknown_face_encoding) # 识别结果列表

print("这张照片是乔布斯吗? {}".format(results[0]))
print("这张照片是马云吗? {}".format(results[1]))


Cuarto, el resultado

这张照片是乔布斯吗? False
这张照片是马云吗? True

Supongo que te gusta

Origin blog.csdn.net/seek97/article/details/108684075
Recomendado
Clasificación