import cv2 as cv
import dlib
# 打开
filename = 'C:/Users/to_bo/Desktop/1.jpg'
img = cv.imread(filename)
# 返回检测器
detector = dlib.get_frontal_face_detector()
# 返回人脸框
faces = detector(img, 1)
# 假设有多个人脸框被返回,依次遍历
for i, d in enumerate(faces):
# 画框框
cv.rectangle(
img,
tuple([d.left(), d.top()]),
tuple([d.right(), d.bottom()]),
(0, 255, 255),
2
)
# 输出
cv.imshow('img', img)
# 结束
cv.waitKey(0)
cv.destroyAllWindows()
68标点
import cv2 as cv
import dlib
# 打开
path = 'C:/Users/to_bo/Desktop/1.jpg'
img = cv.imread(path)
# 返回检测器
detector = dlib.get_frontal_face_detector()
# 返回人脸框
faces = detector(img, 1)
# 返回定位关键点
predictor = dlib.shape_predictor(
'C:/Users/to_bo/Desktop/1.dat'
)
# 假设有多个人脸框被返回,依次遍历
for face in faces:
# 框框里面定位人脸关键点
shape = predictor(img, face)
# 遍历所有(68)点,打印出其坐标,并标记
for p in shape.parts():
cv.circle(img, (p.x, p.y), 1, (255, 0, 0), -1)
# 输出
cv.imshow("image", img)
# 结束
cv.waitKey(0)
cv.destroyAllWindows()
视频predictor = dlib.shape_predictor()关键点预测器用法
detector = dlib.get_frontal_face_detector()获取人脸框的用法
import cv2 as cv
import dlib
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(
'C:/Users/to_bo/Desktop/1.dat'
)
cap = cv.VideoCapture(0, cv.CAP_DSHOW)
if not cap.isOpened():
print("Can not open camera")
exit(0)
while True:
ret, frame = cap.read()
if not ret:
print("Can not receive frame")
break
faces = detector(frame, 1)
for face in faces:
shape = predictor(frame, face)
for p in shape.parts():
cv.circle(frame, (p.x, p.y), 2, (0, 255, 0), -1)
cv.imshow('img', frame)
if cv.waitKey(1) & 0xFF == 27:
break
cap.release()
cv.destroyAllWindows()
补充
detector.run()的识别(不太精确)
import cv2 as cv
import dlib
img = cv.imread('C:/Users/to_bo/Desktop/2.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
detector = dlib.get_frontal_face_detector()
# predictor = dlib.shape_predictor('C:/Users/to_bo/Desktop/1.dat')
faces = detector(gray, 1)
# for face in faces:
# points = predictor(gray, face)
# for p in points.parts():
# cv.circle(img, (p.x, p.y), 1, (0, 255, 0), -1)
# cv.namedWindow('img', cv.WINDOW_NORMAL)
# cv.imshow('img', img)
# cv.waitKey(0)
# cv.destroyWindow('img')
dets, scores, idx = detector.run(img, 1, -1)
for i, d in enumerate(dets):
print("Detection {}, score: {}, face_type:{}".format(
d, scores[i], idx[i]))
if scores[i] > 0.8:
cv.rectangle(img, (d.left(), d.top()), (d.right(), d.bottom()), (0, 255, 255), 2)
cv.putText(
img,
str(scores[i]),
(d.left(), d.bottom()),
cv.FONT_HERSHEY_TRIPLEX,
1,
(0, 255, 0),
2,
cv.LINE_AA
)
cv.namedWindow('img', cv.WINDOW_NORMAL)
cv.imshow('img', img)
cv.waitKey(0)
cv.destroyAllWindows()



