环境配置与依赖安装
使用dlib进行人脸相关任务前,需确保环境配置正确。Python 3.6及以上版本是基础要求,建议使用虚拟环境隔离依赖。
安装核心依赖库:
pip install dlib opencv-python numpy imutils
注意:dlib的安装可能因系统环境差异需要额外步骤。在Windows上,可通过预编译的whl文件安装;Linux/MacOS可能需要CMake和Boost库支持。
人脸检测实现
dlib提供基于HOG特征和线性分类器的快速人脸检测器。以下代码加载预训练模型并检测图像中的人脸:
import dlib
import cv2
# 加载HOG人脸检测器
detector = dlib.get_frontal_face_detector()
# 读取图像并转为灰度
image = cv2.imread("test.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = detector(gray, 1)
# 绘制检测框
for face in faces:
x, y, w, h = face.left(), face.top(), face.width(), face.height()
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Output", image)
cv2.waitKey(0)
人脸关键点定位
dlib的68点关键点检测模型需要额外下载shape_predictor_68_face_landmarks.dat。关键点定位代码示例:
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
for face in faces:
landmarks = predictor(gray, face)
# 绘制所有关键点
for n in range(68):
x = landmarks.part(n).x
### 环境配置与依赖安装
使用dlib进行人脸相关任务前,需确保环境配置正确。Python 3.6及以上版本是基础要求,建议使用虚拟环境隔离依赖。
安装核心依赖库:
```bash
pip install dlib opencv-python numpy imutils
注意:dlib的安装可能因系统环境差异需要额外步骤。在Windows上,可通过预编译的whl文件安装;Linux/MacOS可能需要CMake和Boost库支持。
人脸检测实现
dlib提供基于HOG特征和线性分类器的快速人脸检测器。以下代码加载预训练模型并检测图像中的人脸:
import dlib
import cv2
# 加载HOG人脸检测器
detector = dlib.get_frontal_face_detector()
# 读取图像并转为灰度
image = cv2.imread("test.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = detector(gray, 1)
# 绘制检测框
for face in faces:
x, y, w, h = face.left(), face.top(), face.width(), face.height()
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Output", image)
cv2.waitKey(0)
人脸关键点定位
dlib的68点关键点检测模型需要额外下载shape_predictor_68_face_landmarks.dat。关键点定位代码示例:
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
for face in faces:
landmarks = predictor(gray, face)
# 绘制所有关键点
for n in range(68):
x = landmarks.part(n).x
1463

被折叠的 条评论
为什么被折叠?



