几十行代码实现基于opencv的人脸识别(python)

一、简介

        本项目是一个简单的人脸识别系统,通过提前将人脸图片以人名命名的形式存入文件夹ImagesAttendance中,程序会通过摄像头读取人脸数据如果找到匹配人脸就会将对应图片的名称提取出来放入attendance.csv文件中,同时在摄像头界面中会框出人脸并显示名字,效果图如下:

  

二、代码说明

        首先当然是对库的安装, 其实这个项目唯一不好办的地方也在这里,就是关于face_recognition库的安装,要按照face_recognition库首先得安装cmake、dlib。当在安装dlib时会出现报错,本站大多数资源回答提供了两种解决方案,一种是安装visual stdio和c++库,但是那玩意太大了,而且如果你不用C++的话似乎也起不到什么作用,而且成功率并不高。另一种方法是安装anaconda,通过创建python3.6的虚拟环境来安装对应的dlib whl文件,因为目前集成好的whl文件最多只能支持到python3.6,这种方法也适用于tensorflow的安装,但是这种方法对新手并不友好。所有我在这里建议你安装python3.10版本,我提供了一个python3.10版本对应的dlib whl文件将放在文章末尾。有需要的自取。下载完这个文件之后就可以安装你的库了这里提供命令行安装的方法,win+R输入cmd打开命令行依次输入

pip install cmake
pip install boost
pip install numpy
pip install 对应路径下的whl文件
pip install dlib

接着就可以安装face_recognition库和opencv库了

pip install face-recognition
pip install opencv-python

这里因为我并没有使用pycharm而是sublimetext,所以我又装了一个按键检测的库用于退出程序,按空格键退出。(sublimetext并没有调试功能,而摄像头窗口又是循环检测的所以关闭窗口并没有用,算是一个bug吧,不过按空格结束程序还是可以正常退出的)

import cv2 as cv
import numpy as np
import face_recognition
import os
from datetime import datetime
import keyboard

后续的代码内容就比较简单了

选择存储图片的文件夹路径,读取所有图片的名称存放在列表当中并打印出来

path = 'ImagesAttendance'
images = []
classNames = []
myList = os.listdir(path)
print(myList)
for cl in myList:
	curImg = cv.imread(f'{path}/{cl}')
	images.append(curImg)
	classNames.append(os.path.splitext(cl)[0])
print(classNames)

读取存入文件夹图片的人脸数据

def findEncodings(images):
	encodeList = []
	for img in images:
		img = cv.cvtColor(img,cv.COLOR_BGR2RGB)
		encode = face_recognition.face_encodings(img)[0]
		encodeList.append(encode)
	return encodeList

 将匹配成功的结果写入到Attendance.csv文件中

def markAttendance(name):
	with open('Attendance.csv','r+') as f:
		myDataList = f.readlines()
		nameList = []
		for line in myDataList:
			entry = line.split(',')
			nameList.append(entry[0])
		if name not in nameList:
			now = datetime.now()
			dtString = now.strftime('%H:%M:%S')
			f.writelines(f'\n{name},{dtString}')

 主程序,实时检测摄像头人脸数据并与已知的人脸数据作匹配,匹配成功则调用markAttendance函数将姓名写入到Attendance.csv文件中。

cap = cv.VideoCapture(0)

while True:
	success,img = cap.read()
	imgS = cv.resize(img,(0,0),None,0.25,0.25)
	imgS = cv.cvtColor(imgS,cv.COLOR_BGR2RGB)

	facesCurFrame = face_recognition.face_locations(imgS)
	encodesCurFrame = face_recognition.face_encodings(imgS,facesCurFrame)

	for encodeFace,faceLoc in zip(encodesCurFrame,facesCurFrame):
		matches = face_recognition.compare_faces(encodeListKown,encodeFace)
		faceDis = face_recognition.face_distance(encodeListKown,encodeFace)
		#print(faceDis)
		matchIndex = np.argmin(faceDis)

		if matches[matchIndex]:
			name = classNames[matchIndex].upper()
			#print(name)
			y1,x2,y2,x1 = faceLoc
			y1,x2,y2,x1 = y1*4,x2*4,y2*4,x1*4
			cv.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)
			cv.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv.FILLED)
			cv.putText(img,name,(x1+6,y2-6),cv.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
			markAttendance(name)

最后,按空格退出循环结束程序

	cv.imshow('Webcam',img)
	cv.waitKey(1)
	if keyboard.is_pressed(' '):
		break

 三、完整代码

import cv2 as cv
import numpy as np
import face_recognition
import os
from datetime import datetime
import keyboard

path = 'ImagesAttendance'
images = []
classNames = []
myList = os.listdir(path)
print(myList)
for cl in myList:
	curImg = cv.imread(f'{path}/{cl}')
	images.append(curImg)
	classNames.append(os.path.splitext(cl)[0])
print(classNames)

def findEncodings(images):
	encodeList = []
	for img in images:
		img = cv.cvtColor(img,cv.COLOR_BGR2RGB)
		encode = face_recognition.face_encodings(img)[0]
		encodeList.append(encode)
	return encodeList

def markAttendance(name):
	with open('Attendance.csv','r+') as f:
		myDataList = f.readlines()
		nameList = []
		for line in myDataList:
			entry = line.split(',')
			nameList.append(entry[0])
		if name not in nameList:
			now = datetime.now()
			dtString = now.strftime('%H:%M:%S')
			f.writelines(f'\n{name},{dtString}')


encodeListKown = findEncodings(images)
print('Encoding Complete')

cap = cv.VideoCapture(0)

while True:
	success,img = cap.read()
	imgS = cv.resize(img,(0,0),None,0.25,0.25)
	imgS = cv.cvtColor(imgS,cv.COLOR_BGR2RGB)

	facesCurFrame = face_recognition.face_locations(imgS)
	encodesCurFrame = face_recognition.face_encodings(imgS,facesCurFrame)

	for encodeFace,faceLoc in zip(encodesCurFrame,facesCurFrame):
		matches = face_recognition.compare_faces(encodeListKown,encodeFace)
		faceDis = face_recognition.face_distance(encodeListKown,encodeFace)
		#print(faceDis)
		matchIndex = np.argmin(faceDis)

		if matches[matchIndex]:
			name = classNames[matchIndex].upper()
			#print(name)
			y1,x2,y2,x1 = faceLoc
			y1,x2,y2,x1 = y1*4,x2*4,y2*4,x1*4
			cv.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)
			cv.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv.FILLED)
			cv.putText(img,name,(x1+6,y2-6),cv.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
			markAttendance(name)

	cv.imshow('Webcam',img)
	cv.waitKey(1)
	if keyboard.is_pressed(' '):
		break

whl文件在这里

https://github.com/Simthwan/Face_recognition_system_based_on_face-recognition_library 

  • 18
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用OpenCV人脸识别,你可以按照以下步骤来实现: 首先,在项目文件夹下创建一个脚本文件。 然后,导入OpenCV库并指定待检测的图片和人脸识别模型的路径。你可以使用以下代码预准备操作: import cv2 filename = 'OIP-C.jpg' pathface = 'B:\\Python\\Practic\\Face recognition\\cascades\\haarcascade_frontalface_default.xml' 接下来,定义一个函数来进人脸检测。在这个函数中,你需要加载人脸识别模型并读取待检测的图片。然后,将图片转换为灰度图像,使用人脸识别模型对其进检测,并将检测到的人脸位置标注在图像上。最后,显示标注后的图像,并保存结果图像。 def detect(filename): face_cascade = cv2.CascadeClassifier(pathface) img = cv2.imread(filename) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: img = cv2.rectangle(img, (x, y), (x+w, y+h), (255,0,0), 2) cv2.namedWindow('Face recognition') cv2.imshow('Face recognition', img) cv2.imwrite('./Try.jpg', img) cv2.waitKey(0) 最后,调用detect函数并传入待检测的图片文件名即可进人脸识别。 detect(filename) 以上就是使用OpenCV人脸识别Python代码。请确保你已正确安装了OpenCV库,并将人脸识别模型文件(haarcascade_frontalface_default.xml)放置在正确的路径下。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [基于OpenCV-Python实现人脸识别](https://blog.csdn.net/weixin_52978638/article/details/124287279)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值