通过face_landmarks()在Python中获取面部轮廓
发布时间:2023-12-27 07:42:19
在Python中,我们可以使用dlib库的face_landmarks()函数来获取面部轮廓的关键点坐标。以下是一个例子,展示了如何使用face_landmarks()函数来获取面部轮廓。
首先,我们需要安装dlib库。在命令提示符中执行以下命令:
pip install dlib
接下来,我们将导入所需的库和模块:
import dlib import cv2 import numpy as np import matplotlib.pyplot as plt
然后,我们需要加载一个人脸图像,并用dlib的正面人脸检测器找到人脸的边界框。我们可以使用OpenCV库来加载和显示图像:
image = cv2.imread('path/to/your/image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
detector = dlib.get_frontal_face_detector()
faces = detector(gray)
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)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.show()
现在,我们已经找到了人脸的边界框,接下来我们将使用face_landmarks()函数来获取面部轮廓的关键点坐标:
predictor = dlib.shape_predictor('path/to/shape_predictor_68_face_landmarks.dat')
for face in faces:
landmarks = predictor(gray, face)
for n in range(68):
x = landmarks.part(n).x
y = landmarks.part(n).y
cv2.circle(image, (x, y), 4, (0, 0, 255), -1)
在上述代码中,我们首先加载了一个用于面部特征点检测的预训练模型(shape_predictor_68_face_landmarks.dat)。然后,我们对每个人脸的边界框应用预测器,获取面部轮廓的关键点坐标。最后,我们在图像上绘制了这些关键点。
最后,我们可以使用plt.imshow()函数来显示带有面部轮廓的图像:
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) plt.show()
完整的代码示例,包括加载图像、检测人脸、提取面部轮廓关键点坐标和显示图像的部分,如下所示:
import dlib
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('path/to/your/image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
detector = dlib.get_frontal_face_detector()
faces = detector(gray)
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)
predictor = dlib.shape_predictor('path/to/shape_predictor_68_face_landmarks.dat')
for face in faces:
landmarks = predictor(gray, face)
for n in range(68):
x = landmarks.part(n).x
y = landmarks.part(n).y
cv2.circle(image, (x, y), 4, (0, 0, 255), -1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.show()
在运行这段代码时,请确保替换图像文件的路径和形状预测器的路径。
上述代码示例演示了如何使用face_landmarks()函数通过dlib库在Python中获取面部轮廓的关键点坐标,并在图像上显示这些关键点。该函数非常强大,可以应用于面部识别、姿态估计、面部表情分析等应用中。
