基于OpenCV的Python人脸识别、检测、框选
(遍历目录下所有照片依次识别 视频随时标注)

移步:
https://blog.csdn.net/weixin_53403301/article/details/125121329
【优秀毕设】基于OpenCV的人脸识别打卡/签到/考勤管理系统(最简基本库开发、可基于树莓派)

一、功能概览

可以实现在摄像头下实时的人脸识别、检测、框选功能

原理是将摄像头下的图像人脸和存放照片的目录下的人脸依次进行对比 调用百度的API人脸识别接口 返回相似度的值进行识别

识别成功和失败均有提示 成功时能将对应的信息写入到识别记录中 并终止程序 当所有照片对比后均失败则提示失败 终止程序

窗口利用tkinter函数所写 利用PIL和opencv对图像进行处理 最后将识别结果和人脸框选图像在窗口中显示出来

人脸框选功能用到了opencv官方的人脸识别器 然后利用opencv画出相应外框即可

另外在测试时 用matplotlib.pyplot的相关函数进行输出图像的测试

文件资源包:(文章末尾有百度网盘版)https://download.csdn.net/download/weixin_53403301/66918342

主要代码为工程包内的api_face.py和gui_face_new.py文件

对应识别速度更快的版本为api_face_faster.py和gui_face_new_faster.py文件

另外 gui_face.py文件所对应的程序功能为选择任一目录下的指定图像进行识别 在我之前的文章中有写到 gui_face_new.py文件是在其上的改进

之前的文章和资源:
https://blog.csdn.net/weixin_53403301/article/details/117464715
https://download.csdn.net/download/weixin_53403301/19651352?spm=1001.2014.3001.5503

另外还有应用在树莓派和89C52单片机上的硬件控制版本:
https://blog.csdn.net/weixin_53403301/article/details/118575731
https://download.csdn.net/download/weixin_53403301/20086349

如下图为源文件根目录下的所有文件图示

二、使用说明

主要代码为工程包内的api_face.py和gui_face_new.py文件 运行gui_face_new.py文件即可工作

对应识别速度更快的版本为api_face_faster.py和gui_face_new_faster.py文件

OpenCV版本号为4.40.46 4.5.1版本以上调用摄像头会出现很明显的色差问题

需要在img目录先放入照片 最好为正脸证件照

tmp目录为摄像头截图的临时文件目录

运行程序 点击“使用相机识别”则识别开始 依次对img目录下的照片和摄像头内容进行对比识别

返回的相似度值大于80则成功 小于80则失败

若识别成功 则不在遍历目录下的剩余文件 直接提示成功窗口 中断识别

若识别失败 则继续遍历目录下的剩余文件进行识别 直到识别成功

若所有文件都以识别完 但仍然未识别成功 则提示失败窗口 中断识别

已有的识别记录为Windows系统下创建

Linux系统下的识别记录若为乱码 则需要更改code编码 或删除后重新运行程序 自动建立

在Linux系统建立的识别记录文件 在Windows环境下可以正常读取 不受影响

三、分部测试功能程序

1.遍历目录功能
采用os库遍历img目录下的所有文件 并将其文件名存入到列表中
再利用opencv读取 mat进行显示测试
代码如下:

# -*- coding: utf-8 -*-
"""
Created on Sun Aug  1 11:16:18 2021@author: 16016
"""import cv2
import osimport matplotlib.pyplot as plt # 调用matplotlib绘图库
plt.rcParams['font.sans-serif'] = ['SimHei'] # 载入字体def pshow(words,picture):plt.imshow(picture[:,:,::-1])   # 将读取的图片以RGB转换为BGRplt.title(words), plt.xticks([]), plt.yticks([])plt.show() # 显示图片dir_name='./img'
fileimg_list = []
fileimg_list=os.listdir(dir_name)
file_num=len(fileimg_list)
i=0
while True:if i<file_num:print(i)img=cv2.imread(dir_name + '/' + fileimg_list[i])    pshow(fileimg_list[i],img)i=i+1else:break

运行结果如图所示:

2.界面获取目录功能
此功能是应用在gui_face.py文件夹 目的是通过按钮选择图像并输出图像路径
代码如下:

#coding=utf-8#建立容器
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import *
import tkinter.messagebox
tk=Tk()
tk.title("个人GUI界面学习")
mainfarm=Frame(tk,width=800, height=100,bg="black")
mainfarm.grid_propagate(0)
mainfarm.grid()
fram=Frame(mainfarm,width=400, height=100,bg="black")
fram.grid_propagate(0)
fram.grid()e = Entry(fram)
e.grid(row=0,column=2)e.delete(0, END)  # 将输入框里面的内容清空
e.insert(0, '选择人像图片')
filepath=StringVar()
def filefound():filepath= askopenfilename()print (filepath)e.delete(0, END)  # 将输入框里面的内容清空e.insert(0, filepath)#button1=Button(fram,text="button1").grid(row=0,column=1)
button2=Button(fram,text="选择文件",command=filefound).grid(row=0,column=3)
#print (fram.size())mainloop()

运行结果如图所示:

3.人脸框选功能
加载目录下的opencv官方人脸识别器(haarcascade_frontalface_default.xml) 进行识别后画出外框
代码如下:

import cv2
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 载入字体#print('请输入需录入的人脸图片路径/文件名:')
#pic_name=input()# 利用MATLAB显示图片
def pshow(words,picture):plt.imshow(picture[:,:,::-1])plt.title(words), plt.xticks([]), plt.yticks([])plt.show()# 图像路径 我用的相对路径
filepath = 'img/123.jpg'
# 读取文件
faceImg = cv2.imread(filepath)
# 转换灰色
gray = cv2.cvtColor(faceImg,cv2.COLOR_BGR2GRAY)# 加载人脸识别分类器
# 官方已有的分类器  https://github.com/opencv/opencv/tree/master/data/haarcascades
# github的不好下载, 可以从码云上找
# Python\Python38-32\Lib\site-packages\cv2\data  这个目录下也有
classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
color = (0,255,0)# 识别器进行识别
faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))
# 识别器返回一个列表, 里面是每个识别出的人脸的区域, 左上和右下定点的坐标
# print(faceRects)  #[[113  42  60  60]]    前两个值是左上定点的xy坐标,第三个是width 宽度对应y的变化, 另一个就是x的# 判断识别结果集合长度
if len(faceRects):for faceRect in faceRects:x,y,w,h = faceRect# 框选出人脸   最后一个参数2是框线宽度cv2.rectangle(faceImg,(x, y), (x + h, y + w), color, 2)pshow('1',faceImg)
# 显示图像

运行结果如下:

4.摄像头及框选功能
同上一个功能 不过是对摄像头图像进行实时的框选 并实时显示 同时还加上了人眼部分框选(haarcascade_eye.xml)
通过opencv进行显示 同时按esc键退出
代码如下:

import cv2cap = cv2.VideoCapture(0)  # 开启摄像头# 循环读取图像
while True:ok, img = cap.read()  # 读取摄像头图像if ok is False:print('无法读取到摄像头!')breakfaceImg = imggray = cv2.cvtColor(faceImg,cv2.COLOR_BGR2GRAY)# 加载人脸识别分类器# 官方已有的分类器  https://github.com/opencv/opencv/tree/master/data/haarcascades# github的不好下载, 可以从码云上找# Python\Python38-32\Lib\site-packages\cv2\data  这个目录下也有classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')color = (0,255,0)# 识别器进行识别faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))if len(faceRects):for faceRect in faceRects:x,y,w,h = faceRect# 框选出人脸   最后一个参数2是框线宽度cv2.rectangle(faceImg,(x, y), (x + h, y + w), color, 2)# 转换灰色gray = cv2.cvtColor(faceImg,cv2.COLOR_BGR2GRAY)# 加载人脸识别分类器# 官方已有的分类器  https://github.com/opencv/opencv/tree/master/data/haarcascades# github的不好下载, 可以从码云上找# Python\Python38-32\Lib\site-packages\cv2\data  这个目录下也有classifier = cv2.CascadeClassifier('haarcascade_eye.xml')color = (255,0,0)# 识别器进行识别faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))if len(faceRects):for faceRect in faceRects:x,y,w,h = faceRect# 框选出人脸   最后一个参数2是框线宽度cv2.rectangle(faceImg,(x, y), (x + h, y + w), color, 2)#faceImg= cv2.cvtColor(faceImg,cv2.COLOR_RGB2BGR)cv2.imshow("faceImg",faceImg)# 展示图像k = cv2.waitKey(10)  # 键盘值if k == 27:   # 通过esc键退出摄像break# 关闭摄像头
cap.release()
cv2.destroyAllWindows()

运行结果如下:

5.延时功能
此功能主要用于测试time库 获取系统时间的功能
测试这个功能的目的主要是为了在主程序中 通过控制时间减少资源的使用 使其每隔一段时间读取、识别一次(0.1s)
主程序中 识别函数为一个循环 读取一次摄像头并进行人脸识别 若识别成功 则中断循环 若识别失败 也跳出循环
代码如下:

# -*- coding: utf-8 -*-
"""
Created on Tue Jun  1 00:14:45 2021@author: ZHOU
"""import time
import threadingdef delay(a):print( time.time(),'10s',a)print( time.time())s = threading.Timer(10,delay,("delay",))s.start()print( time.time())def main():print('1')delay(10)print('2')main()

运行结果如下:
延时时间为10s

四、主程序部分
1.API算法部分
调用 requests的HTTP协议库
调用os多操作系统接口库
调用base64编码库
调用JavaScript Object Notation数据交换格式
登入百度的人脸识别API 然后对给出的两个图像进行对比识别 输出相相似度
所有相关功能和函数的语句已在代码中注释好了
代码如下:(第一段为常规版,第二段为快速版)

# -*- coding: utf-8 -*-
"""
Created on Mon May 31 23:40:16 2021@author: ZHOU
"""#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests # 调用 requests的HTTP协议库
import os # 调用os多操作系统接口库
import base64 # 调用base64编码库
import json # 调用JavaScript Object Notation数据交换格式ACCESS_TOKEN = ''
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #去掉文件名,返回目录 # ID,KEY的配置信息
INFO_CONFIG = { 'ID': '15788358','API_KEY': 'ohtGa5yYoQEZ8Try8lnL99UK','SECRET_KEY': 'qaDjyuXkf5MZ28g5C8pwFngDZenhswC3'
}# URL配置
URL_LIST_URL = {# ACCESS_TOKEN_URL用于获取ACCESS_TOKEN, POST请求,#  grant_type必须参数,固定为client_credentials,client_id必须参数,应用的API Key,client_secre 必须参数,应用的Secret Key.'ACCESS_TOKEN_URL': 'https://aip.baidubce.com/oauth/2.0/token?' + 'grant_type=client_credentials&client_id={API_KEYS}&client_secret={SECRET_KEYS}&'.format(API_KEYS=INFO_CONFIG['API_KEY'], SECRET_KEYS=INFO_CONFIG['SECRET_KEY']),# 登入人脸识别机器学习库'FACE_PLATE': 'https://aip.baidubce.com/rest/2.0/face/v3/match',}class AccessTokenSuper(object):passclass AccessToken(AccessTokenSuper): # 定义登陆API大类def getToken(self):accessToken = requests.post(url=URL_LIST_URL['ACCESS_TOKEN_URL']) #登入网址accessTokenJson = accessToken.json()if dict(accessTokenJson).get('error') == 'invalid_client':return '获取accesstoken错误,请检查API_KEY,SECRET_KEY是否正确!'return accessTokenJsonACCESS_TOKEN = AccessToken().getToken()['access_token']LICENSE_PLATE_URL = URL_LIST_URL['FACE_PLATE'] + '?access_token={}'.format(ACCESS_TOKEN)class faceSuper(object):passclass face(faceSuper): # 定义图像输入大类def __init__(self, image=None, image2=None): # 定义初始化函数self.HEADER = {'Content-Type': 'application/json; charset=UTF-8',}if image is not None:     # 没有图像1imagepath = os.path.exists(image)if imagepath == True:images = imagewith open(images, 'rb') as images:img1 = base64.b64encode(images.read())else:print("图像1不存在")returnif image2 is not None:    # 没有图像2imagepath2 = os.path.exists(image2)if imagepath2 == True:images2 = image2with open(images2, 'rb') as images2:img2 = base64.b64encode(images2.read())else:print("图像2不存在")returnself.img = img1self.imgs = img2self.IMAGE_CONFIG1 = {"image": str(img1, 'utf-8'), "image_type": "BASE64"}self.IMAGE_CONFIG2 = {"image": str(img2, 'utf-8'), "image_type": "BASE64"}self.IMAGE_CONFIG = json.dumps([self.IMAGE_CONFIG1, self.IMAGE_CONFIG2])def postface(self):  # 定义从服务器进行数据获取函数if (self.img==None and self.imgs==None):return '图像不存在'face = requests.post(url=LICENSE_PLATE_URL, headers=self.HEADER, data=self.IMAGE_CONFIG)# 登陆服务器获取数据return face.json()    # 输出结果def facef(FA1, FA2): # 人脸识别逻辑函数testAccessToken = AccessToken() # 获取API配置testface = face(image=FA1, image2=FA2) # 赋值给图像输入大类result_json = testface.postface()  # 从服务器获取数据result = result_json['result']['score'] #输出结果print('人脸相似度:', result)if result > 80: # 识别结果大于80则成功print("人脸匹配成功!")
#    if result < 20:
#        print("未检测到人脸!")else:print("人脸匹配失败!")return '人脸相似度:' + str(result), result # 输出字符串结果
# -*- coding: utf-8 -*-
"""
Created on Mon May 31 23:40:16 2021@author: ZHOU
"""#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests # 调用 requests的HTTP协议库
import os # 调用os多操作系统接口库
import base64 # 调用base64编码库
import json # 调用JavaScript Object Notation数据交换格式ACCESS_TOKEN = ''
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #去掉文件名,返回目录 # ID,KEY的配置信息
INFO_CONFIG = { 'ID': '15788358','API_KEY': 'ohtGa5yYoQEZ8Try8lnL99UK','SECRET_KEY': 'qaDjyuXkf5MZ28g5C8pwFngDZenhswC3'
}# URL配置
URL_LIST_URL = {# ACCESS_TOKEN_URL用于获取ACCESS_TOKEN, POST请求,#  grant_type必须参数,固定为client_credentials,client_id必须参数,应用的API Key,client_secre 必须参数,应用的Secret Key.'ACCESS_TOKEN_URL': 'https://aip.baidubce.com/oauth/2.0/token?' + 'grant_type=client_credentials&client_id={API_KEYS}&client_secret={SECRET_KEYS}&'.format(API_KEYS=INFO_CONFIG['API_KEY'], SECRET_KEYS=INFO_CONFIG['SECRET_KEY']),# 登入人脸识别机器学习库'FACE_PLATE': 'https://aip.baidubce.com/rest/2.0/face/v3/match',}class AccessTokenSuper(object):passclass AccessToken(AccessTokenSuper): # 定义登陆API大类def getToken(self):accessToken = requests.post(url=URL_LIST_URL['ACCESS_TOKEN_URL']) #登入网址accessTokenJson = accessToken.json()if dict(accessTokenJson).get('error') == 'invalid_client':return '获取accesstoken错误,请检查API_KEY,SECRET_KEY是否正确!'return accessTokenJsonACCESS_TOKEN = AccessToken().getToken()['access_token']LICENSE_PLATE_URL = URL_LIST_URL['FACE_PLATE'] + '?access_token={}'.format(ACCESS_TOKEN)class faceSuper(object):passclass face(faceSuper): # 定义图像输入大类def __init__(self, image=None, image2=None): # 定义初始化函数self.HEADER = {'Content-Type': 'application/json; charset=UTF-8',}if image is not None:     # 没有图像1imagepath = os.path.exists(image)if imagepath == True:images = imagewith open(images, 'rb') as images:img1 = base64.b64encode(images.read())else:print("图像1不存在")returnif image2 is not None:    # 没有图像2imagepath2 = os.path.exists(image2)if imagepath2 == True:images2 = image2with open(images2, 'rb') as images2:img2 = base64.b64encode(images2.read())else:print("图像2不存在")returnself.img = img1self.imgs = img2self.IMAGE_CONFIG1 = {"image": str(img1, 'utf-8'), "image_type": "BASE64"}self.IMAGE_CONFIG2 = {"image": str(img2, 'utf-8'), "image_type": "BASE64"}self.IMAGE_CONFIG = json.dumps([self.IMAGE_CONFIG1, self.IMAGE_CONFIG2])def postface(self):  # 定义从服务器进行数据获取函数if (self.img==None and self.imgs==None):return '图像不存在'face = requests.post(url=LICENSE_PLATE_URL, headers=self.HEADER, data=self.IMAGE_CONFIG)# 登陆服务器获取数据return face.json()    # 输出结果def facef(FA1, FA2): # 人脸识别逻辑函数testAccessToken = AccessToken() # 获取API配置testface = face(image=FA1, image2=FA2) # 赋值给图像输入大类result_json = testface.postface()  # 从服务器获取数据result = result_json['result']['score'] #输出结果print('人脸相似度:', result)
#    if result > 80: # 识别结果大于80则成功
#        print("人脸匹配成功!")
#    if result < 20:
#        print("未检测到人脸!")
#    else:
#        print("人脸匹配失败!")return '人脸相似度:' + str(result), result # 输出字符串结果

此函数需要配合网络进行使用
单独运行时不报错则可以连接上API

利用facef(FA1, FA2)函数 传入入两个图像值 则能进行识别

若API出错 则改为

    'ID': '15050553','API_KEY': 'rlRrtRL5oRdXGh71jgg1OmyN','SECRET_KEY': 'dK5TpuTAZn2nw5eVpspZLmF5Qs1Uu8A1'

2.界面程序部分
测试时 利用mat显示图像 pshow函数展示 在实际运行中 为了加快运行速度 将测试部分的代码注释掉了
所有相关功能和函数的语句已在代码中注释好了
(测试图片中为原始版本,文字提示中没有姓名,现代码已更新为包含姓名提示的版本)
代码如下:(第一段为常规版,第二段为快速版)

# -*- coding: utf-8 -*-
"""
Created on Mon May 31 23:39:19 2021@author: ZHOU
"""# -*- coding: utf-8 -*-import tkinter as tk # 调用窗口tk
from tkinter import ttk
from tkinter.filedialog import *
import tkinter.messagebox
from PIL import Image, ImageTk # 调用图像处理库pillow
import api_face # 调用本地函数库 用于登入外部机器学习库并调用人脸识别函数
import cv2 # 调用OpenCV图像处理库
import threading # 调用threading多线程运行库
import time # 调用系统时间戳库
import os # 调用os多操作系统接口库
import matplotlib.pyplot as plt # 调用matplotlib绘图库
plt.rcParams['font.sans-serif'] = ['SimHei'] # 载入字体#print('请输入需录入的人脸图片路径/文件名:')
#pic_name=input()# 利用matplotlib显示图片函数
def pshow(words,picture):plt.imshow(picture[:,:,::-1])   # 将读取的图片以RGB转换为BGRplt.title(words), plt.xticks([]), plt.yticks([])plt.show() # 显示图片class Login(ttk.Frame): # 定义窗口大类def __init__(self, win):ttk.Frame.__init__(self, win)frame0 = ttk.Frame(self)frame1 = ttk.Frame(self)win.title("人脸识别")win.minsize(1240, 620)self.center_window()    # 执行中置窗口函数self.thread_run = None   # 赋值 线程1默认关闭self.thread_run2 = None    # 线程2默认关闭self.camera = None    # 摄像头默认关闭#定义tk窗口属性#self.pilImage = Image.open("img/start.png")#self.tkImage = ImageTk.PhotoImage(image=self.pilImage)#self.image_ctl = tk.Label(frame0, image=self.tkImage)#self.image_ctl.pack()frame0.pack(side=TOP, fill=tk.Y, expand=1)frame1.pack(side=TOP, fill=tk.Y, expand=1)self.facer = ttk.Label(frame1, text='', font=('Times', '20')) # 字体self.facer.pack()#        def filefound(): # 定义获取图片路径的函数
#            filepath= askopenfilename() # 获取文件路径
#            pic_name=filepath
#            self.pic_path2 = pic_name # 赋值给图像2
#
#            pshow('所选人像图片',pic_img) # 显示所选图片self.pic_path3='./star.png'
#        pic_img=cv2.imread(self.pic_path3)
#        pic_xz = pic_img.shape # 计算图像大小
#        pic_h=pic_xz[0] # 得出图片高度
#        pic_w=pic_xz[1] # 得出图片宽度
#        turn_w=pic_w*500/pic_h # 限制最大高度为580 以防窗口过小不完全显示 等比例转换宽度
#        turn_w=int(turn_w)
#            print('人像图像大小(高 宽):',pic_h,pic_w)
#            print ('路径:',filepath)
#            # 在tk窗口中显示所选图片self.pilImage = Image.open(self.pic_path3)            self.photo = self.pilImage.resize((500,500)) # 限制最大高度为580 等比缩放显示self.tkImage = ImageTk.PhotoImage(image=self.photo)self.image_ctl = tk.Label(frame0, image=self.tkImage)self.image_ctl.pack()
#            #e.delete(0, END)  # 将输入框里面的内容清空
#            #e.insert(0, filepath)
#
#        #button2=Button(frame1,text="button2",command=filefound).grid(row=0,column=3)
#        # 按钮1 调用filefound函数 获取选择图片的路径 并赋值给self.pic_path2 输出图像
#        self.face_button1 = ttk.Button(frame1, text="1. 选择人像图片", width=15, command=filefound)
#        self.face_button1.pack(side=TOP)        # 按钮2 调用摄像头函数self.url_face_button = ttk.Button(frame1, text="使用相机识别", width=15, command=self.cv_face)self.url_face_button.pack(side=TOP)#self.file_pic_button = ttk.Button(frame1, text="本地文件识别", width=15, command=self.file_pic)#self.file_pic_button.pack(side=TOP)self.pack(fill=tk.BOTH, expand=tk.YES, padx="10", pady="10")#使弹出的窗体处于屏幕的中间位置def center_window(self):screenwidth = log.winfo_screenwidth()    # 获取屏幕分辨率宽screenheight = log.winfo_screenheight()  # 获取屏幕分辨率高log.update()  # 更新窗口width = log.winfo_width()    # 重新赋值height = log.winfo_height()size = '+%d+%d' % ((screenwidth - width)/2, (screenheight - height)/2)# 重新赋值大小 大小为屏幕大小/2log.geometry(size)   # 以新大小定义窗口#    def file1(self):
#        self.pic_path = askopenfilename(title="选择识别图片", filetypes=[("jpg图片", "*.jpg"), ("png图片", "*.png")])def cv_face(self):   # 调用摄像头函数if self.thread_run:if self.camera.isOpened(): # 如果已经打开则关闭self.camera.release()print("关闭摄像头")self.camera = Noneself.thread_run = Falsereturnif self.camera is None: # 如果没有摄像头则尝试打开self.camera = cv2.VideoCapture(1) # 利用OpenCV调用外摄像头if not self.camera.isOpened(): # 如果没有打开 则调用内摄像头self.camera = Noneprint("没有外置摄像头")self.camera = cv2.VideoCapture(0) # 用OpenCV调用内摄像头if not self.camera.isOpened(): # 如果没有打开 则打开失败print("没有内置摄像头")tkinter.messagebox.showinfo('警告', '摄像头打开失败!')self.camera = Nonereturnelse:print("打开内置摄像头")else:print("打开外置摄像头")self.thread = threading.Thread(target=self.video_thread) # 多线程函数执行摄像头运行函数self.thread.setDaemon(True)self.thread.start()self.thread_run = Truedef video_thread(self): # 开始摄像头运行self.thread_run = True # 多线程1开启self.thread2 = threading.Thread(target=self.video_pic)self.thread2.setDaemon(True)self.thread2.start()self.thread_run2 = Truewhile self.thread_run: # 循环一直调用摄像头_, img_bgr = self.camera.read() # 以bgr格式读取摄像头内的截图 gray = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2GRAY) # 灰度转换# 在CV官方机器学习库内加载人脸识别分类器                # Python\Python38-32\Lib\site-packages\cv2\data  这个目录下也有classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')color = (0,255,0) # 绿色线# 识别器进行识别faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))# 识别器返回一个列表, 里面是每个识别出的人脸的区域, 左上和右下定点的坐标# print(faceRects)  #[[113  42  60  60]]    前两个值是左上定点的xy坐标,第三个是width 宽度对应y的变化, 另一个就是x的# 判断识别结果集合长度if len(faceRects):for faceRect in faceRects:x,y,w,h = faceRect# 用矩形框选出人脸   最后一个参数2是框线宽度cv2.rectangle(img_bgr,(x, y), (x + h, y + w), color, 2)                 img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) # 颜色转换im = Image.fromarray(img)w, h = im.sizepil_image_resized = self.resize(w, h, im) # 调整大小函数self.imgtk = ImageTk.PhotoImage(image=pil_image_resized)self.image_ctl.configure(image=self.imgtk)print("结束运行")def video_pic(self): # 视频截图保存及框选函数dir_name='./img' # 给出图片目录路径fileimg_list = [] # 建立列表型图片列表fileimg_list=os.listdir(dir_name) # 获取目录下文件名file_num=len(fileimg_list) # 获取列表长度fileimg_num=0   # 定义文件序号初始值为0self.thread_run2 = True     # 开启多线程predict_time = time.time() # 获得系统时间while self.thread_run2: # 循环读取if time.time() - predict_time > 0.1: #每0.1s读取一次摄像头截图print("正在识别中")_, img_bgr = self.camera.read() # 重新读取摄像头图像cv2.imwrite("tmp/test.jpg", img_bgr) #利用cv写入到tmp/test.jpg路径下
#                test_pic=cv2.imread('tmp/test.jpg') # 重新读取截图
#                pshow('识别截图',test_pic) # 显示截图
#
#                # 图像路径 我用的相对路径
#                face_mark = 'tmp/test.jpg'
#                # 读取截图
#                faceImg = cv2.imread(face_mark)
#                # 转换灰色
#                gray = cv2.cvtColor(faceImg,cv2.COLOR_RGB2GRAY) # 由于tmp/test.jpg路径下的已经转换成RGB保存 所以不用再进行BGR转换
#
#                # 在CV官方机器学习库内加载人脸识别分类器
#                # Python\Python38-32\Lib\site-packages\cv2\data  这个目录下也有
#                classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#                color = (0,255,0) # 绿色线
#
#                # 识别器进行识别
#                faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))
#                # 识别器返回一个列表, 里面是每个识别出的人脸的区域, 左上和右下定点的坐标
#                # print(faceRects)  #[[113  42  60  60]]    前两个值是左上定点的xy坐标,第三个是width 宽度对应y的变化, 另一个就是x的
#
#                # 判断识别结果集合长度
#                if len(faceRects):
#                    for faceRect in faceRects:
#                        x,y,w,h = faceRect
#                        # 用矩形框选出人脸   最后一个参数2是框线宽度
#                        cv2.rectangle(faceImg,(x, y), (x + h, y + w), color, 2)
#
#
#                pshow('识别结果',faceImg)    # 输出框选结果图像并显示
#                cv2.imwrite("tmp/test2.jpg", faceImg)self.pic_path = "tmp/test.jpg" # 重新读取摄像头截图
#                self.pilImage = Image.open(self.pic_path)
#                self.tkImage = ImageTk.PhotoImage(image=self.pilImage)
#                self.image_ctl = tk.Label(frame0, image=self.tkImage)
#                self.image_ctl.pack()try:if fileimg_num<file_num: #当文件序号小于总列表长度时#print(fileimg_num)#img=cv2.imread(dir_name + '/' + fileimg_list[fileimg_num])    #pshow(fileimg_list[fileimg_num],img)self.pic_path2 = dir_name + '/' + fileimg_list[fileimg_num] # 给出pic_path2的值为目录名+/+文件名#print(self.pic_path2)
#                        self.pic_path2='./img/111.jpg'facestr, result = api_face.facef(self.pic_path, self.pic_path2) # 调用api_face库的人脸识别函数self.facer.configure(text=str(facestr))#self.pic() # 对摄像头图像进行尺度变换if result > 80: #识别结果大于80humantitle='  姓名:  '+fileimg_list[fileimg_num].partition('.')[0]+"  人脸匹配成功!  \n"print(humantitle) # 输出人像文件文件名tkinter.messagebox.showinfo('提示', humantitle) # tk窗口提示try:f=open("识别记录.txt","r")fi=open("识别记录.txt","a")txt=time.ctime()fi.write(txt+humantitle)f.close()fi.close() # 将识别成功的记录保存在txt文件下except:f=open("识别记录.txt","w")txt=time.ctime()f.write(txt+humantitle)f.close()# close_window()# os.system("python3 ./main.py")#if result < 20:#    tkinter.messagebox.showinfo('提示', '未检测到人脸!')breakelse: # 小于80失败fileimg_num=fileimg_num+1 # 文件序号+1else: # 超出文件列表长度tkinter.messagebox.showinfo('提示', '查无此人!人脸匹配失败!')breakexcept:passpredict_time = time.time()      # 读取时间          print("识别结束")# 看门狗程序(调试用)# 防止程序关闭时进入死循环跑飞#print('请输入任意值以继续,否则请关闭窗口以终止程序:')#a=input()#print(a)pass#    def file_pic(self): #识别函数
#        dir_name='./img'
#        fileimg_list = []
#        fileimg_list=os.listdir(dir_name)
#        file_num=len(fileimg_list)
#        fileimg_num=0
#        while True:
#            if fileimg_num<file_num:
#                print(fileimg_num)
#                img=cv2.imread(dir_name + '/' + fileimg_list[fileimg_num])
#                pshow(fileimg_list[fileimg_num],img)
#                self.pic_path2 = dir_name + '/' + fileimg_list[fileimg_num]
#                print(self.pic_path2)
##                self.pic_path2='./img/111.jpg'
#                facestr, result = api_face.facef(self.pic_path, self.pic_path2) # 调用api_face库的人脸识别函数
#                self.facer.configure(text=str(facestr))
#                        #self.pic() # 对摄像头图像进行尺度变换
#                if result > 80: #识别结果大于80
#                    tkinter.messagebox.showinfo('提示', '人脸匹配成功!') # tk窗口提示
#                    print('人像图片路径:'+self.pic_path2) # 输出人像文件路径
#                    try:
#                        f=open("识别记录.txt","r")
#                        fi=open("识别记录.txt","a")
#                        txt=time.ctime()
#                        fi.write(txt+'   人像图片路径:   '+self.pic_path2+"     人脸匹配成功! \n")
#                        f.close()
#                        fi.close() # 将识别成功的记录保存在txt文件下
#                    except:
#                        f=open("识别记录.txt","w")
#                        txt=time.ctime()
#                        f.write(txt+'   人像图片路径:   '+self.pic_path2+"     人脸匹配成功! \n")
#                        f.close()
#
#
#
#                            # close_window()
#                            # os.system("python3 ./main.py")
#                        #if result < 20:
#                        #    tkinter.messagebox.showinfo('提示', '未检测到人脸!')
#                        break
#                    else: # 小于80失败
#                        fileimg_num=fileimg_num+1
#
#
#            else:
#                tkinter.messagebox.showinfo('提示', '人脸匹配失败!')
#                break#    def pic(self): # 对摄像头图像进行尺度变换
#        self.pilImage3 = Image.open(self.pic_path) # 用pillow读取摄像头图像
#        w, h = self.pilImage3.size # 计算大小赋值给宽 高
#        pil_image_resized = self.resize(w, h, self.pilImage3) # 调整大小函数
#        self.tkImage3 = ImageTk.PhotoImage(image=pil_image_resized)
#        self.image_ctl.configure(image=self.tkImage3) # 输出结果def resize(self, w, h, pil_image): # 调整大小函数w_box = 1000 # 定义最大宽度h_box = 500 # 最大高度f1 = 1.0*w_box/w # 最大值/真实值f2 = 1.0*h_box/hfactor = min([f1, f2]) # 取最小值width = int(w*factor) # 用最小值*对应值 调整到最大定义值 等比调整另一个值height = int(h*factor)return pil_image.resize((width, height), Image.ANTIALIAS) # 输出调整def close_window():print("已关闭人脸识别")if Login.thread_run:Login.thread_run = FalseLogin.thread.join(2.0)log.destroy()if __name__ == '__main__':log = tk.Tk()login = Login(log)# close,退出输出destroylog.protocol('清除窗口', close_window)# 进入消息循环log.mainloop()
# -*- coding: utf-8 -*-
"""
Created on Mon May 31 23:39:19 2021@author: ZHOU
"""# -*- coding: utf-8 -*-import tkinter as tk # 调用窗口tk
from tkinter import ttk
from tkinter.filedialog import *
import tkinter.messagebox
from PIL import Image, ImageTk # 调用图像处理库pillow
import api_face_faster # 调用本地函数库 用于登入外部机器学习库并调用人脸识别函数
import cv2 # 调用OpenCV图像处理库
import threading # 调用threading多线程运行库
import time # 调用系统时间戳库
import os # 调用os多操作系统接口库
import matplotlib.pyplot as plt # 调用matplotlib绘图库
plt.rcParams['font.sans-serif'] = ['SimHei'] # 载入字体#print('请输入需录入的人脸图片路径/文件名:')
#pic_name=input()# 利用matplotlib显示图片函数
def pshow(words,picture):plt.imshow(picture[:,:,::-1])   # 将读取的图片以RGB转换为BGRplt.title(words), plt.xticks([]), plt.yticks([])plt.show() # 显示图片class Login(ttk.Frame): # 定义窗口大类def __init__(self, win):ttk.Frame.__init__(self, win)frame0 = ttk.Frame(self)frame1 = ttk.Frame(self)win.title("人脸识别")win.minsize(1240, 620)self.center_window()    # 执行中置窗口函数self.thread_run = None   # 赋值 线程1默认关闭self.thread_run2 = None    # 线程2默认关闭self.camera = None    # 摄像头默认关闭#定义tk窗口属性#self.pilImage = Image.open("img/start.png")#self.tkImage = ImageTk.PhotoImage(image=self.pilImage)#self.image_ctl = tk.Label(frame0, image=self.tkImage)#self.image_ctl.pack()frame0.pack(side=TOP, fill=tk.Y, expand=1)frame1.pack(side=TOP, fill=tk.Y, expand=1)self.facer = ttk.Label(frame1, text='', font=('Times', '20')) # 字体self.facer.pack()#        def filefound(): # 定义获取图片路径的函数
#            filepath= askopenfilename() # 获取文件路径
#            pic_name=filepath
#            self.pic_path2 = pic_name # 赋值给图像2
#
#            pshow('所选人像图片',pic_img) # 显示所选图片self.pic_path3='./star.png'
#        pic_img=cv2.imread(self.pic_path3)
#        pic_xz = pic_img.shape # 计算图像大小
#        pic_h=pic_xz[0] # 得出图片高度
#        pic_w=pic_xz[1] # 得出图片宽度
#        turn_w=pic_w*500/pic_h # 限制最大高度为580 以防窗口过小不完全显示 等比例转换宽度
#        turn_w=int(turn_w)
#            print('人像图像大小(高 宽):',pic_h,pic_w)
#            print ('路径:',filepath)
#            # 在tk窗口中显示所选图片self.pilImage = Image.open(self.pic_path3)            self.photo = self.pilImage.resize((500,500)) # 限制最大高度为580 等比缩放显示self.tkImage = ImageTk.PhotoImage(image=self.photo)self.image_ctl = tk.Label(frame0, image=self.tkImage)self.image_ctl.pack()
#            #e.delete(0, END)  # 将输入框里面的内容清空
#            #e.insert(0, filepath)
#
#        #button2=Button(frame1,text="button2",command=filefound).grid(row=0,column=3)
#        # 按钮1 调用filefound函数 获取选择图片的路径 并赋值给self.pic_path2 输出图像
#        self.face_button1 = ttk.Button(frame1, text="1. 选择人像图片", width=15, command=filefound)
#        self.face_button1.pack(side=TOP)        # 按钮2 调用摄像头函数self.url_face_button = ttk.Button(frame1, text="使用相机识别", width=15, command=self.cv_face)self.url_face_button.pack(side=TOP)#self.file_pic_button = ttk.Button(frame1, text="本地文件识别", width=15, command=self.file_pic)#self.file_pic_button.pack(side=TOP)self.pack(fill=tk.BOTH, expand=tk.YES, padx="10", pady="10")#使弹出的窗体处于屏幕的中间位置def center_window(self):screenwidth = log.winfo_screenwidth()    # 获取屏幕分辨率宽screenheight = log.winfo_screenheight()  # 获取屏幕分辨率高log.update()  # 更新窗口width = log.winfo_width()    # 重新赋值height = log.winfo_height()size = '+%d+%d' % ((screenwidth - width)/2, (screenheight - height)/2)# 重新赋值大小 大小为屏幕大小/2log.geometry(size)   # 以新大小定义窗口#    def file1(self):
#        self.pic_path = askopenfilename(title="选择识别图片", filetypes=[("jpg图片", "*.jpg"), ("png图片", "*.png")])def cv_face(self):   # 调用摄像头函数if self.thread_run:if self.camera.isOpened(): # 如果已经打开则关闭self.camera.release()print("关闭摄像头")self.camera = Noneself.thread_run = Falsereturnif self.camera is None: # 如果没有摄像头则尝试打开self.camera = cv2.VideoCapture(1) # 利用OpenCV调用外摄像头if not self.camera.isOpened(): # 如果没有打开 则调用内摄像头self.camera = Noneprint("没有外置摄像头")self.camera = cv2.VideoCapture(0) # 用OpenCV调用内摄像头if not self.camera.isOpened(): # 如果没有打开 则打开失败print("没有内置摄像头")tkinter.messagebox.showinfo('警告', '摄像头打开失败!')self.camera = Nonereturnelse:print("打开内置摄像头")else:print("打开外置摄像头")self.thread = threading.Thread(target=self.video_thread) # 多线程函数执行摄像头运行函数self.thread.setDaemon(True)self.thread.start()self.thread_run = Truedef video_thread(self): # 开始摄像头运行self.thread_run = True # 多线程1开启self.thread2 = threading.Thread(target=self.video_pic)self.thread2.setDaemon(True)self.thread2.start()self.thread_run2 = Truewhile self.thread_run: # 循环一直调用摄像头_, img_bgr = self.camera.read() # 以bgr格式读取摄像头内的截图 gray = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2GRAY) # 灰度转换# 在CV官方机器学习库内加载人脸识别分类器                # Python\Python38-32\Lib\site-packages\cv2\data  这个目录下也有classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')color = (0,255,0) # 绿色线# 识别器进行识别faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))# 识别器返回一个列表, 里面是每个识别出的人脸的区域, 左上和右下定点的坐标# print(faceRects)  #[[113  42  60  60]]    前两个值是左上定点的xy坐标,第三个是width 宽度对应y的变化, 另一个就是x的# 判断识别结果集合长度if len(faceRects):for faceRect in faceRects:x,y,w,h = faceRect# 用矩形框选出人脸   最后一个参数2是框线宽度cv2.rectangle(img_bgr,(x, y), (x + h, y + w), color, 2)                 img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) # 颜色转换im = Image.fromarray(img)w, h = im.sizepil_image_resized = self.resize(w, h, im) # 调整大小函数self.imgtk = ImageTk.PhotoImage(image=pil_image_resized)self.image_ctl.configure(image=self.imgtk)print("结束运行")def video_pic(self): # 视频截图保存及框选函数dir_name='./img' # 给出图片目录路径fileimg_list = [] # 建立列表型图片列表fileimg_list=os.listdir(dir_name) # 获取目录下文件名file_num=len(fileimg_list) # 获取列表长度fileimg_num=0   # 定义文件序号初始值为0self.thread_run2 = True     # 开启多线程
#        predict_time = time.time() # 获得系统时间while self.thread_run2: # 循环读取
#            if time.time() - predict_time > 0.1: #每0.1s读取一次摄像头截图
#            print("正在识别中")_, img_bgr = self.camera.read() # 重新读取摄像头图像cv2.imwrite("tmp/test.jpg", img_bgr) #利用cv写入到tmp/test.jpg路径下
#                test_pic=cv2.imread('tmp/test.jpg') # 重新读取截图
#                pshow('识别截图',test_pic) # 显示截图
#
#                # 图像路径 我用的相对路径
#                face_mark = 'tmp/test.jpg'
#                # 读取截图
#                faceImg = cv2.imread(face_mark)
#                # 转换灰色
#                gray = cv2.cvtColor(faceImg,cv2.COLOR_RGB2GRAY) # 由于tmp/test.jpg路径下的已经转换成RGB保存 所以不用再进行BGR转换
#
#                # 在CV官方机器学习库内加载人脸识别分类器
#                # Python\Python38-32\Lib\site-packages\cv2\data  这个目录下也有
#                classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#                color = (0,255,0) # 绿色线
#
#                # 识别器进行识别
#                faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))
#                # 识别器返回一个列表, 里面是每个识别出的人脸的区域, 左上和右下定点的坐标
#                # print(faceRects)  #[[113  42  60  60]]    前两个值是左上定点的xy坐标,第三个是width 宽度对应y的变化, 另一个就是x的
#
#                # 判断识别结果集合长度
#                if len(faceRects):
#                    for faceRect in faceRects:
#                        x,y,w,h = faceRect
#                        # 用矩形框选出人脸   最后一个参数2是框线宽度
#                        cv2.rectangle(faceImg,(x, y), (x + h, y + w), color, 2)
#
#
#                pshow('识别结果',faceImg)    # 输出框选结果图像并显示
#                cv2.imwrite("tmp/test2.jpg", faceImg)self.pic_path = "tmp/test.jpg" # 重新读取摄像头截图
#                self.pilImage = Image.open(self.pic_path)
#                self.tkImage = ImageTk.PhotoImage(image=self.pilImage)
#                self.image_ctl = tk.Label(frame0, image=self.tkImage)
#                self.image_ctl.pack()try:if fileimg_num<file_num: #当文件序号小于总列表长度时#print(fileimg_num)#img=cv2.imread(dir_name + '/' + fileimg_list[fileimg_num])    #pshow(fileimg_list[fileimg_num],img)self.pic_path2 = dir_name + '/' + fileimg_list[fileimg_num] # 给出pic_path2的值为目录名+/+文件名#print(self.pic_path2)
#                        self.pic_path2='./img/111.jpg'facestr, result = api_face_faster.facef(self.pic_path, self.pic_path2) # 调用api_face库的人脸识别函数self.facer.configure(text=str(facestr))#self.pic() # 对摄像头图像进行尺度变换if result > 80: #识别结果大于80humantitle='  姓名:  '+fileimg_list[fileimg_num].partition('.')[0]+"  人脸匹配成功!  \n"print(humantitle) # 输出人像文件文件名tkinter.messagebox.showinfo('提示', humantitle) # tk窗口提示                          try:f=open("识别记录.txt","r")fi=open("识别记录.txt","a")txt=time.ctime()fi.write(txt+humantitle)f.close()fi.close() # 将识别成功的记录保存在txt文件下except:f=open("识别记录.txt","w")txt=time.ctime()f.write(txt+humantitle)f.close()# close_window()# os.system("python3 ./main.py")#if result < 20:#    tkinter.messagebox.showinfo('提示', '未检测到人脸!')breakelse: # 小于80失败fileimg_num=fileimg_num+1 # 文件序号+1else: # 超出文件列表长度tkinter.messagebox.showinfo('提示', '查无此人!人脸匹配失败!')breakexcept:pass
#                predict_time = time.time()      # 读取时间
#            print("识别结束")# 看门狗程序(调试用)# 防止程序关闭时进入死循环跑飞#print('请输入任意值以继续,否则请关闭窗口以终止程序:')#a=input()#print(a)pass#    def file_pic(self): #识别函数
#        dir_name='./img'
#        fileimg_list = []
#        fileimg_list=os.listdir(dir_name)
#        file_num=len(fileimg_list)
#        fileimg_num=0
#        while True:
#            if fileimg_num<file_num:
#                print(fileimg_num)
#                img=cv2.imread(dir_name + '/' + fileimg_list[fileimg_num])
#                pshow(fileimg_list[fileimg_num],img)
#                self.pic_path2 = dir_name + '/' + fileimg_list[fileimg_num]
#                print(self.pic_path2)
##                self.pic_path2='./img/111.jpg'
#                facestr, result = api_face.facef(self.pic_path, self.pic_path2) # 调用api_face库的人脸识别函数
#                self.facer.configure(text=str(facestr))
#                        #self.pic() # 对摄像头图像进行尺度变换
#                if result > 80: #识别结果大于80
#                    tkinter.messagebox.showinfo('提示', '人脸匹配成功!') # tk窗口提示
#                    print('人像图片路径:'+self.pic_path2) # 输出人像文件路径
#                    try:
#                        f=open("识别记录.txt","r")
#                        fi=open("识别记录.txt","a")
#                        txt=time.ctime()
#                        fi.write(txt+'   人像图片路径:   '+self.pic_path2+"     人脸匹配成功! \n")
#                        f.close()
#                        fi.close() # 将识别成功的记录保存在txt文件下
#                    except:
#                        f=open("识别记录.txt","w")
#                        txt=time.ctime()
#                        f.write(txt+'   人像图片路径:   '+self.pic_path2+"     人脸匹配成功! \n")
#                        f.close()
#
#
#
#                            # close_window()
#                            # os.system("python3 ./main.py")
#                        #if result < 20:
#                        #    tkinter.messagebox.showinfo('提示', '未检测到人脸!')
#                        break
#                    else: # 小于80失败
#                        fileimg_num=fileimg_num+1
#
#
#            else:
#                tkinter.messagebox.showinfo('提示', '人脸匹配失败!')
#                break#    def pic(self): # 对摄像头图像进行尺度变换
#        self.pilImage3 = Image.open(self.pic_path) # 用pillow读取摄像头图像
#        w, h = self.pilImage3.size # 计算大小赋值给宽 高
#        pil_image_resized = self.resize(w, h, self.pilImage3) # 调整大小函数
#        self.tkImage3 = ImageTk.PhotoImage(image=pil_image_resized)
#        self.image_ctl.configure(image=self.tkImage3) # 输出结果def resize(self, w, h, pil_image): # 调整大小函数w_box = 1000 # 定义最大宽度h_box = 500 # 最大高度f1 = 1.0*w_box/w # 最大值/真实值f2 = 1.0*h_box/hfactor = min([f1, f2]) # 取最小值width = int(w*factor) # 用最小值*对应值 调整到最大定义值 等比调整另一个值height = int(h*factor)return pil_image.resize((width, height), Image.ANTIALIAS) # 输出调整def close_window():print("已关闭人脸识别")if Login.thread_run:Login.thread_run = FalseLogin.thread.join(2.0)log.destroy()if __name__ == '__main__':log = tk.Tk()login = Login(log)# close,退出输出destroylog.protocol('清除窗口', close_window)# 进入消息循环log.mainloop()

五、最终测试
1.识别成功测试
读取img目录下所有图像 对摄像头图像依次进行对比识别 相似度不断变化 当大于80时 输出成功提示 并获取图像名称、写入记录文档中
如图所示,我的图像位于img目录下的第4个 列表序号为3 程序应在识别到此的时候停止
(测试图片中为原始版本,文字提示中没有姓名,现代码已更新为包含姓名提示的版本)

初始界面:

点击“使用相机识别”后开始开启摄像头识别
如图所示为识别成功结果:

点击确认后终止程序
在识别记录.txt文档中可以看到刚刚的照片名称 识别时间

在实际运行时 对前三个图像的相似度较低 最大只有36 成功后程序停止 不再对后面的图像进行识别
如图所示:


2.识别失败功能测试
戴上口罩进行识别(或删掉目录下对应人物的图像) 相似度达不到80 遍历的图片都无法成功识别 最后提示失败

删除对应图像:


戴上口罩 相似度最高只有60多 识别失败:


六、总结
参考文章链接:
https://blog.csdn.net/weixin_53403301/article/details/118575731
https://blog.csdn.net/weixin_53403301/article/details/118005313
https://blog.csdn.net/weixin_53403301/article/details/117464715
主程序部分代码注释完整 基本上每一行都有说明和注释 直接看主程序代码就可以弄懂其原理
关于树莓派的人脸识别 目前还是之前的版本(指定图像进行识别) 由于还没开学 没有硬件可以测试 所以尚未加入遍历目录下所有文件的功能进行 等加上以后 我会单独再写一篇
树莓派效果展示图:

最后 此次开源系统的百度网盘资源包:
链接:https://pan.baidu.com/s/1oOZKc_I3G5OdcRDpkZM7yQ
提取码:hml1

这里是光电Mike Zhou 一位光电专业在读的网易独家签约音乐人
歌手页面:
https://music.163.com/#/artist?id=12115205

【优秀课设】基于OpenCV的Python人脸识别、检测、框选(遍历目录下所有照片依次识别 视频随时标注)相关推荐

  1. 【优秀课设】基于OpenCV-Python的树莓派人脸识别及89C52单片机控制系统设计(指定照片进行识别、遍历目录下所有照片依次识别)

    基于OpenCV-Python的树莓派人脸识别及89C52单片机控制系统设计 (指定照片进行识别) 参照之前的文章所改进 增加视频随时标注功能 https://blog.csdn.net/weixin ...

  2. 【项目实战课】基于Pytorch的PFLD人脸关键点检测实战

    欢迎大家来到我们的项目实战课,本期内容是<基于Pytorch的PFLD人脸关键点检测实战>.所谓项目课,就是以简单的原理回顾+详细的项目实战的模式,针对具体的某一个主题,进行代码级的实战讲 ...

  3. Python Tricks(九)—— 递归遍历目录下所有文件

    递归的一大应用场景便在于不知其层数. import os def list_filename(path):for d in os.listdir(path):d = path + '/' + d # ...

  4. 【优秀课设】基于OpenCV-Python的摄像头人脸检测追踪控制系统

    基于OpenCV-Python的摄像头人脸检测追踪控制系统 资源: download.csdn.net/download/weixin_53403301/25496828 采用OpenCV-Pytho ...

  5. 【优秀毕设】基于OpenCV的人脸识别打卡/签到/考勤管理系统(最简基本库开发、可基于树莓派)

    [优秀毕设]基于OpenCV的人脸识别打卡/签到/考勤管理系统(最简基本库开发.可基于树莓派) 该系统利用Harr级联检测和LPBH进行人脸检测和训练.识别 利用Tkinter完成界面搭建 利用Fla ...

  6. 【毕业设计/课程设计】基于opencv的高精度人脸识别考勤系统设计与实现

    文章目录 0 项目说明 1 需求分析 2 总体设计 3 详细设计 4 程序运行结果测试与分析 5 实验心得 6 项目源码 0 项目说明 基于opencv的高精度人脸识别考勤系统设计与实现 提示:适合用 ...

  7. 【项目实战课】基于Pytorch的StyleGAN人脸属性(表情、年龄、性别)编辑实战

    欢迎大家来到我们的项目实战课,本期内容是<基于Pytorch的StyleGAN人脸属性编辑实战>.所谓项目实战课,就是以简单的原理回顾+详细的项目实战的模式,针对具体的某一个主题,进行代码 ...

  8. 【项目实战课】基于Pytorch的DCGAN人脸嘴部表情图像生成实战

    欢迎大家来到我们的项目实战课,本期内容是<基于Pytorch的DCGAN人脸嘴部表情图像生成实战>. 所谓项目实战课,就是以简单的原理回顾+详细的项目实战的模式,针对具体的某一个主题,进行 ...

  9. 【项目实战课】基于Pytorch的UGATIT人脸动漫风格化实战

    欢迎大家来到我们的项目实战课,本期内容是<基于Pytorch的UGATIT人脸动漫风格化实战>.所谓项目课,就是以简单的原理回顾+详细的项目实战的模式,针对具体的某一个主题,进行代码级的实 ...

最新文章

  1. window下lamp环境搭建
  2. 打开高效文本编辑之门_调用Linux的sed命令
  3. 没有与参数列表匹配的 重载函数 strcpy_s 实例_Zemax光学设计实例(84)Ftheta扫描平场透镜的设计...
  4. Shell 脚本——测试命令
  5. 如何让apache支持.htaccess 解决Internal Server Error The server …错误
  6. java 编译参数_java – 为什么要编译?代码似乎打破了类型参数的约束
  7. 用计算机进行频谱分析时,实验四-利用FFT对信号进行频谱分析1112
  8. 有关Cassandra节点之间的通信:Gossip【译】
  9. IIS6.0目录解析漏洞原理/复现
  10. nlp基础—11.条件随机场模型(CRF)模型补充
  11. JS/VUE 自定义效验 统一社会信用代码 营业执照注册号
  12. 反编译PyInstaller打包后的exe为py源码
  13. 基于集成学习模型的估价预测(量化投资)
  14. java特殊字符大全_java 字符串特殊符号
  15. 计算机音乐谱策马奔腾,策马奔腾简谱
  16. 计算机税率函数,2018最新按5000元个税Excel计算公式,帮你整理齐了!
  17. 解读Secondary NameNode的功能
  18. mysql 二进制 nodejs_Linux 下安装NodeJS (二进制包)
  19. 编译原理 实验四 LR(0)分析法(LR0分析表的自动生成)
  20. Mac 应用中支持Dark Mode(深色模式)

热门文章

  1. 数据库新技术前沿总结
  2. 2022年下半年 系统架构师,论文-软件开发模型(Software Development Model)
  3. JS鼠标滑过图片时切换图片
  4. 价值千万的职业操盘手教程
  5. 虚拟串口软件:VSPD的使用
  6. Q:python编码
  7. Photoshop的时间轴是灰色的,不能使的解决方法
  8. IT耳朵IT桔子:2017年人工智能行业发展研究报告白皮书
  9. 00 Mybatis之简介与入门
  10. Guide to Elliptic Curve Cryptography (ECC椭圆曲线算法1)