1.安装包依赖

安装好依赖包opencv-python、face-recognition、tkinter

pip install opencv-python
pip install face-recognition

安装可以参考之前的文章:​​Python 基于OpenCV+face_recognition实现人脸捕捉与人脸识别​​。由于python3以上版本已经将tkinter内置到环境,所以这里不需要单独安装依赖。

2.代码示例

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

#选择一个图片并显示在界面上
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)
showHandledImg(choosepath)

#处理人脸特征
def handleFacialFeatures(image, face_marks):
for marks_dict in face_marks:
for marks_key in marks_dict.keys():
for point in marks_dict[marks_key]:
cv2.circle(image, point, 2, (0,0,255), -1)
return image

#显示处理后的照片
def showHandledImg(choosepath):
frame=cv2.imread(choosepath)
frame=cv2.resize(src=frame,dsize=(530,750))
#转成RGB灰度图
frameRGB=cv2.cvtColor(src=frame,code=cv2.COLOR_BGR2RGB)
#获取人脸关键点
face_marks = face_recognition.face_landmarks(frameRGB, None, "large")
#返回处理后的结果
imgHandledArr = handleFacialFeatures(frame, face_marks)
#将处理后的照片数组转成图片
imgHandled = Image.fromarray(imgHandledArr)
img = ImageTk.PhotoImage(imgHandled)
lableShowImage2.config(image=img)
lableShowImage2.image = img
lableShowImage2.place(x=630, y=70, width=530, height=750)

if __name__ == '__main__':
app = tk.Tk()
#窗体标题
app.title("show pictue")
#窗体大小
app.geometry("1200x900+200+50")
path = tk.StringVar()
#将路径展示框只读
entry = tk.Entry(app, state='readonly', text=path,width = 100)
entry.pack()
#显示原图
lableShowImage = tk.Label(app)
lableShowImage.pack()
#显示处理后的效果图
lableShowImage2 = tk.Label(app)
lableShowImage2.pack()
#点击选择图片触发choosepic()方法
buttonSelImage = tk.Button(app, text='choose picture', command=choosepic)
buttonSelImage.pack()
app.mainloop()

3.说明

整个源码中核心就是face_recognition.face_landmarks来获取人脸特征点集合。

face_landmarks(face_imageface_locations=Nonemodel='large')参数说明:

  • face_image:要处理的图像
  • face_locations:可选提供要检查的脸部位置列表,none 表示不确定人脸所在的位置,自动找。
  • model:模型,large获取68个点集合,small获取5个点集合,small处理速度快

Python 基于OpenCV+face_recognition+tkinter实现人脸特征监测_安装包

将图片数据数组转成图片有9种不同的方式,大家可以一一去尝试

modes

描述

1

1位像素,黑和白,存成8位的像素

L

8位像素,黑白

P

8位像素,使用调色板映射到任何其他模式

RGB

3× 8位像素,真彩

RGBA

4×8位像素,真彩+透明通道

CMYK

4×8位像素,颜色隔离

YCbCr

3×8位像素,彩色视频格式

I

32位整型像素

F

32位浮点型像素

4.实现效果 

 

Python 基于OpenCV+face_recognition+tkinter实现人脸特征监测_opencv_02

 

Python 基于OpenCV+face_recognition+tkinter实现人脸特征监测_opencv_03