36.OpenCV的人脸关键点检测——dlib库
dlib库是一个十分好用的机器学习库,其源码均由C++实现,并提供了Python 接口,可广泛适用于很多场景。本实例仅简单示范dlib库中关于人脸关键点技术的Python应用。
可以使用这个代码在windows环境中进行安装:
pip install dlib-bin -i https://pypi.douban.com/simple/
dlib封装了一个人脸关键点提取算法,下载好模型后可直接调用。可以实现的68个点的关键点检测:
对图片中的人脸进行检测:
import cv2
import dlib
image = cv2.imread("Tom2.jpeg")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = detector(gray, 1)
for face in faces: #(x, y, w, h)
cv2.rectangle(image, (face.left(), face.top()), (face.right(), face.bottom()), (0,255,0), 5)
shape = predictor(image, face)
for pt in shape.parts():
pt_position = (pt.x, pt.y)
cv2.circle(image, pt_position, 2, (0, 0, 255), -1)
cv2.imshow("resulr", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import dlib
capture = cv2.VideoCapture(0)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
while True:
ret, frame = capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray, 1)
for face in faces:
cv2.rectangle(frame, (face.left(), face.top()), (face.right(), face.bottom()), (0,255,0), 3)
shape = predictor(gray, face)
for pt in shape.parts():
pt_position = (pt.x, pt.y)
cv2.circle(frame, pt_position, 3, (0,0,255), -1)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imshow("face detection landmark", frame)
capture.release()
cv2.destroyAllWindows()
OpenCV-Python测试用图片、中文官方文档、opencv-4.5.4源码
以上内容简单的介绍了OpenCV-Python的人脸关键点检测,有关Python、数据科学、人工智能等文章后续会不定期发布,请大家多多关注,一键三连哟(●’◡’●)。