Python 基于OpenCV+face_recognition实现人脸捕捉与人脸识别(照片对比)

1.安装包依赖

与上篇通过摄像头动态识别人脸一样,先下载好opencv-python、face-recognition,这里因为使用的是照片对比的方式,特意使用tkinter画了一个简单的GUI方便操作。

在python 3以上版本tkinter是环境自带的,所以这里不需要安装

2.代码示例

import os
import cv2
import numpy as np
import face_recognition
import tkinter as tk  
import tkinter.filedialog
from PIL import Image,ImageTk 

classNames=[]
img_path='Picture'
img_recognition_path='Recognition'
existsEncodeingList=[]
#对人脸集合进行编码进行处理
def findEncodeings(images):
    for img in images:
        #灰度处理
        img=cv2.cvtColor(src=img,code=cv2.COLOR_BGR2RGB)
        #face_encodings对图片对象a_images进行编码并返回数组0位置编码结果
        encode=face_recognition.face_encodings(img)[0]
        existsEncodeingList.append(encode)

#获取当前存储的人脸编码集合
def findExistsEncodeingList(img_path):
    images=[]
    #列出已经上传的所有图片
    imgList=os.listdir(img_path)
    #处理存储的图片得到其人脸编码
    for pic in imgList:
        img=cv2.imread('{}/{}'.format(img_path,pic))
        images.append(img)
        classNames.append(os.path.splitext(pic)[0])
    findEncodeings(images)

#选择并对比图片
def choosepic():
    choosepath = tkinter.filedialog.askopenfilename()
    path.set(choosepath)
    img_open = Image.open(entry.get()).resize((530,750))
    img = ImageTk.PhotoImage(img_open)
    lableShowImage.config(image=img)
    lableShowImage.image = img
    lableShowImage.place(x=30, y=70, width=530, height=750)
    faceRecognition(choosepath)

def faceRecognition(choosepath):
    frame=cv2.imread(choosepath)
    frameRGB=cv2.cvtColor(src=frame,code=cv2.COLOR_BGR2RGB)
    #对摄像头读取的检测人脸
    facesLocate=face_recognition.face_locations(frameRGB)
    #进行特征编码
    faceEncoded=face_recognition.face_encodings(frameRGB,facesLocate)
	#遍历检测的人脸和库中读取的图片进行对比,计算其相似度
    name='unknow'
    for (top,right, bottom,left),face_encoding in zip(facesLocate,faceEncoded):
        #进行匹配
        matchs=face_recognition.compare_faces(existsEncodeingList,face_encoding)
        #计算相似度
        distance=face_recognition.face_distance(existsEncodeingList,face_encoding)
        lab='unknow'
        for index, item in enumerate(distance):
           if item<0.5:
                if matchs[index]:
                    #得到匹配到的图片名称与相似度值
                    lab='name:{}; Similarity:{}'.format(classNames[index],item)
                    name=classNames[index]
                    break
        #初始化面部捕捉框显示绿色
        color1 =(0,255,0)
        if name =='unknow':
            #未能识别的时候显示蓝色
            color1 =(255,0,0)
        #画面部捕捉框
        cv2.rectangle(img=frame,pt1=(left,top),pt2=(right,bottom),color=color1,thickness=3)
        #在捕捉框上添加匹配到的图片信息
        cv2.putText(frame, lab, (left,top-8),cv2.FONT_HERSHEY_SIMPLEX, 0.7, color1, 2)
        cv2.imwrite('{}/{}.png'.format(img_recognition_path,name),frame)
    img_Recognition = Image.open('{}/{}.png'.format(img_recognition_path,name)).resize((530,750))
    img = ImageTk.PhotoImage(img_Recognition)
    lableShowImage2.config(image=img)
    lableShowImage2.image = img
    lableShowImage2.place(x=630, y=70, width=530, height=750)

if __name__ == '__main__':
    findExistsEncodeingList(img_path)
    #生成tk界面 app即主窗口
    app = tk.Tk()  
    #修改窗口titile
    app.title("show pictue")  
    #设置主窗口的大小和位置
    app.geometry("1200x900+200+50")
    #Entry widget which allows displaying simple text.
    path = tk.StringVar()
    entry = tk.Entry(app, state='readonly', text=path,width = 100)
    entry.pack()
    #使用Label显示图片
    lableShowImage = tk.Label(app)
    lableShowImage.pack()
     #使用Label2显示处理后的图片
    lableShowImage2 = tk.Label(app)
    lableShowImage2.pack()
    #选择图片的按钮
    buttonSelImage = tk.Button(app, text='choose picture', command=choosepic)
    buttonSelImage.pack()
    app.mainloop()

3.说明

首先我将需要被识别的人脸的照片预设到项目目录的Picture文件夹下,然后创建一个Recognition目录存放识别过的图片,这样方便在一个界面上展示对比结果照片。

 其实对比结果也可以不用存,直接将处理后的图片缓存直接展示在界面上,这里需要改一下此处的代码,将上述代码注释掉,然后换成下面的那行,通过数组直接转成图片

 但是效果会存在色彩的失真,效果如下:

也尝试了PIL的九种不同图片模式: 1,L,P,RGB,RGBA,CMYK,YCbCr,I,F,最终效果也没达到,大概与我resize((530,750))这个有关,也没继续纠结,有兴趣的同学可以尝试一下。

这里简单提下PIL的九种不同图片模式:

modes描述
11位像素,黑和白,存成8位的像素
L8位像素,黑白
P8位像素,使用调色板映射到任何其他模式
RGB3× 8位像素,真彩
RGBA4×8位像素,真彩+透明通道
CMYK4×8位像素,颜色隔离
YCbCr3×8位像素,彩色视频格式
I32位整型像素
F32位浮点型像素

4.实现效果

 

 

 可以实现简单的人脸对比,Similarity代表相似度值,值越小代表人脸与预设的图片越相似。

下面是一个基于PythonOpenCVface_recognition库的简单人脸识别代码示例: ```python import cv2 import face_recognition # 加载已知的人脸图像和对应的名字 obama_image = face_recognition.load_image_file("obama.jpg") obama_face_encoding = face_recognition.face_encodings(obama_image)[0] biden_image = face_recognition.load_image_file("biden.jpg") biden_face_encoding = face_recognition.face_encodings(biden_image)[0] known_face_encodings = [ obama_face_encoding, biden_face_encoding ] known_face_names = [ "Barack Obama", "Joe Biden" ] # 打开摄像头 cap = cv2.VideoCapture(0) while True: # 读取一帧图像 ret, frame = cap.read() # 转换为RGB图像 rgb_frame = frame[:, :, ::-1] # 检测人脸 face_locations = face_recognition.face_locations(rgb_frame) face_encodings = face_recognition.face_encodings(rgb_frame, face_locations) # 遍历每个检测到的人脸 for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): # 判断是否和已知人脸匹配 matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "Unknown" # 如果匹配到了已知人脸,则获取对应的名字 if True in matches: first_match_index = matches.index(True) name = known_face_names[first_match_index] # 在图像上绘制人脸矩形和名字 cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) # 显示图像 cv2.imshow('Video', frame) # 按下q键退出 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放摄像头和窗口资源 cap.release() cv2.destroyAllWindows() ``` 注意,这个代码示例需要在已经安装了face_recognition库和OpenCV库的Python环境中运行,还需要把`obama.jpg`和`biden.jpg`两个已知人脸图像放在代码所在目录下。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大鱼>

一分也是爱

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

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

打赏作者

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

抵扣说明:

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

余额充值