2019年10月15号
作者:杨轮飞
将会使用到python中的opencv、dlib、sklearn库。
1.先通过opencv+dlib调用摄像头对人脸进行截图保存为数据集
- 先导入库
import cv2
import dlib
import numpy
- 写一个使用dlib检测人脸后对图像的函数,用于输出框出人脸的图像与人脸区域坐上角点和右下角
def dlib_find_face(img, dets):
font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX
minx, miny, maxx, maxy = 640, 640, 0, 0
for k, d in enumerate(dets):
shape = predictor(img, d)
#(x, y, w, h) = face_utils.rect_to_bb(rect)
landmark = numpy.matrix([[p.x, p.y] for p in shape.parts()])
for idx, point in enumerate(landmark):
x, y = (point[0, 0], point[0, 1])
cv2.putText(img, "*", (x, y), font,0.3,(0, 255, 0))
if x > maxx: maxx = x;
if x < minx: minx = x;
if y > maxy: maxy = y;
if y < miny: miny = y;
cv2.rectangle(img, (minx - 10, miny - 10), (maxx + 10, maxy + 10), (0, 255, 0), 2)
return img, (minx, miny), (maxx, maxy)
- 打开摄像头,对图像进行dlib人脸检测,然后将人脸区域保存下来。当保存了32张人脸时推出程序
if __name__=="__main__":
predictor_path = "F:\qq\shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
cap = cv2.VideoCapture(0)
number = 1
name = "wzy"
while True:
sucess, img = cap.read()
temp = img.copy()
temp_gray = cv2.cvtColor(temp, cv2.COLOR_RGB2GRAY)
dets = detector(temp_gray, 1)
k = cv2.waitKey(1)
if k == 27:
break
if len(dets) == 1:
temp, min, max = dlib_find_face(temp, dets)
if k == 32:
face = img[min[1]:max[1], min[0]:max[0]]
face = cv2.resize(face, (64, 64))
cv2.imwrite("face_image\\"+name+"\\"+name+str(number)+".jpg", face)
print("保存成功:"+name+str(number)+".jpg")
number += 1
if number == 33: break;
cv2.imshow("face", temp)
cap.release()
cv2.destroyAllWindows()
得到数据集后第一步算是结束啦~
接下来就是对我们的数据集进行训练了~