安裝的是anaconde3、python3.7.3,3.7環境安裝dlib太麻煩,
在anaconde3中新建環境python3.6.8,
在3.6環境下安裝dlib-19.6.1-cp36-cp36m-win_amd64.whl,下載地址:https://pypi.org/project/dlib/19.6.1/#files
vscode更改配置
其中shape_predictor_68_face_landmarks.dat官方訓練數據下載地址:http://dlib.net/files/,里面還有5點模型。
效果圖如下:
# _*_ coding:utf-8 _*_
import numpy as np
import cv2
import dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("data/shape_predictor_68_face_landmarks.dat")
# cv2讀取圖像
img = cv2.imread("img/test3.jpg")
# 取灰度
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 人臉數rects
rects = detector(img_gray, 0)
for i in range(len(rects)):
landmarks = np.matrix([[p.x, p.y] for p in predictor(img, rects[i]).parts()])
for idx, point in enumerate(landmarks):
# 68點的坐標
pos = (point[0, 0], point[0, 1])
# 利用cv2.circle給每個特征點畫一個圈,共68個
cv2.circle(img, pos, 2, color=(0, 255, 0))
# 利用cv2.putText輸出1-68
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, str(idx + 1), None, font, 0.8, (0, 0, 255), 1, cv2.LINE_AA)
cv2.namedWindow("img", 2)
cv2.imshow("img", img)
cv2.waitKey(0)
攝像頭實時檢測:
#_*_ coding:utf-8 _*_
importnumpy as npimportcv2importdlib
cap=cv2.VideoCapture(0)
detector=dlib.get_frontal_face_detector()
predictor= dlib.shape_predictor("data/shape_predictor_68_face_landmarks.dat")while 1:
ret, img=cap.read()#取灰度
img_gray =cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)#人臉數rects
rects =detector(img_gray, 0)for i inrange(len(rects)):
landmarks= np.matrix([[p.x, p.y] for p inpredictor(img, rects[i]).parts()])for idx, point inenumerate(landmarks):#68點的坐標
pos = (point[0, 0], point[0, 1])#利用cv2.circle給每個特征點畫一個圈,共68個
cv2.circle(img, pos, 2, color=(0, 255, 0))#利用cv2.putText輸出1-68
font =cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, str(idx+ 1), None, font, 0.8, (0, 0, 255), 1, cv2.LINE_AA)
cv2.namedWindow("img", 2)
cv2.imshow("img", img)if cv2.waitKey(1) & 0xFF == ord("q"):break