今日的学习内容:用opencv-python库打开摄像头,定义一个面部正面探测器,并设定脸部图像坐标与尺寸,识别出人脸,并导入拍出的图片
先导入所需的库,注意Python版本要与cv2版本一致,以及dlib版本
opencv-python下载地址
dlib下载地址
import tensorflow as tf
import cv2
import dlib
import numpy as np
#定义面部正面探测器
detector = dlib.get_frontal_face_detector()
#打开摄像头或视频文件
cap = cv2.VideoCapture(0)
#设置外边距
margin = 0.2
frame_count = 0#帧计数
face_count = 0#人脸计数
需要自定义两个文件夹存储图片
while True:
ret,frame = cap.read()
if ret!=True:
print("defeat")
break
frame_count = 1
input_img = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)#转为灰度图
img_h,img_w, _ = np.shape(input_img)#获取图像尺寸
detected = detector(frame,1)
faces = []#脸部图像列表
if len(detected)>0:#当前帧检测到人脸
for i,d in enumerate(detected):
face_count += 1
#脸部图像坐标与尺寸
x1,y1,x2,y2,w,h = d.left(),d.top(),d.right()+1,d.bottom()+1,d.width(),d.height()
#用边距做调整
xw1 = max(int(x1-margin * w), 0)
yw1 = max(int(y1-margin * h), 0)
xw2 = max(int(x2+margin * w), img_w - 1)
yw2 = max(int(y2+margin * h), img_h - 1)
#脸部图像坐标
face = frame[yw1 : yw2+1 , xw1 : xw2+1, :]
if (frame_count % 4 != 0):
#保存人脸图像到dataset/train目录下
file_name = "./dataset/train/one/"+str(frame_count) + "_one"+str(i)+".jpg"
else:
#保存人脸图像到dataset/valid目录下
file_name = "./dataset/valid/one/"+str(frame_count) + "_one"+str(i)+".jpg"
cv2.imwrite(file_name, face)
#绘制边界框
cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2)
#显示单针检测结果
cv2.imshow("Face Detector",frame)
#按esc键结束循环
if(cv2.waitKey(1) & 0xFF) == 27:
break
print(f"已经完成{frame_count}帧检测,保存了{face_count}幅脸部图像")
cap.release()
cv2.destroyAllWindows()
通过修改./dataset/train/one分别在训练集和验证集里面建立四个文件夹,为下次实验室使用。