一、原理
参考前面的博客基于OpenCv+Python+Dlib实现简单人脸数据采集
二、代码实现
1.提取人脸
输入需要录制的人的姓名用来创建对应文件夹来保存图片,通过摄像头捕获到的图片进行人脸检测,当检测到人脸后用矩形进行标注。按下s键进行保存,ESC键盘退出。
import cv2
import dlib
import os
import sys
import random
# 存储位置
output_dir = './output/person/test'
size = 64
# 改变图片的亮度与对比度
def relight(img, light=1, bias=0):
w = img.shape[1]
h = img.shape[0]
# image = []
for i in range(0, w):
for j in range(0, h):
for c in range(3):
tmp = int(img[j, i, c] * light + bias)
if tmp > 255:
tmp = 255
elif tmp < 0:
tmp = 0
img[j, i, c] = tmp
return img
# 使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
# 打开摄像头 参数为输入流,可以为摄像头或视频文件
camera = cv2.VideoCapture(0)
name=input("请输入录入人的姓名:")
index = 1
ok = True
output_dir+= '/' +name
if not os.path.exists(output_dir):
os.makedirs(output_dir)
while ok:
# 从摄像头读取照片
# 读取摄像头中的图像,ok为是否读取成功的判断参数
ok, img = camera.read()
# 转换成灰度图像
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用detector进行人脸检测
dets = detector(img_gray, 1)
for i, d in enumerate(dets):
x1 = d.top() if d.top() > 0 else 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = d.right() if d.right() > 0 else 0
# 截取人脸方框
face = img[x1:y1, x2:y2]
# 绘制矩形框标注人脸
cv2.rectangle(img, tuple([x2, x1]), tuple([y2, y1]), (0, 255, 255), 2)
print('Being processed picture %s' % index)
# 调整图片的对比度与亮度, 对比度与亮度值都取随机数,这样能增加样本的多样性
face = relight(face, random.uniform(0.5, 1.5), random.randint(

该博客介绍了如何使用OpenCV、Dlib库构建一个人脸识别系统,包括人脸检测、特征点提取和人脸识别。首先,通过摄像头捕获人脸并保存,然后计算人脸的128D特征值,将这些特征值存储到CSV文件中。最后,实现实时人脸识别,通过比较新捕获人脸的特征与已知人脸特征的欧氏距离,识别出相似的人脸。
最低0.47元/天 解锁文章
6357

被折叠的 条评论
为什么被折叠?



