Python中使用face_landmarks()生成面部特征点
发布时间:2023-12-27 07:41:25
face_landmarks()是Python的一个函数,可以用于生成图片中人脸的面部特征点。
首先,需要导入所需要的库:dlib、cv2和matplotlib。
import dlib import cv2 import matplotlib.pyplot as plt
接下来,需要加载预训练的人脸检测器,可以使用dlib提供的训练好的模型文件。下载地址:http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
然后,读取一张图片,可以使用cv2库中的imread()函数。需要注意的是,图片读入后是BGR格式,而face_landmarks()函数需要RGB格式的图片,所以需要使用cv2库中的cvtColor()函数将图片转换为RGB格式。
image = cv2.imread("image.jpg")
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
接下来,使用dlib库中的get_frontal_face_detector()函数创建一个人脸检测器。
detector = dlib.get_frontal_face_detector()
然后使用人脸检测器检测图片中的人脸,可以使用detector()函数。该函数返回一个人脸位置的列表。
faces = detector(rgb_image)
接下来,使用循环依次处理每张人脸。使用predictor()函数可以得到人脸的面部特征点列表。
for face in faces:
landmarks = predictor(rgb_image, face)
最后,可以使用matplotlib库中的imshow()函数将图片显示出来,并使用plot()函数绘制出人脸的面部特征点。
plt.imshow(rgb_image)
for point in landmarks.parts():
plt.plot(point.x, point.y, 'ro')
plt.show()
下面是一个完整的例子,包括所有的步骤:
import dlib
import cv2
import matplotlib.pyplot as plt
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
image = cv2.imread("image.jpg")
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
detector = dlib.get_frontal_face_detector()
faces = detector(rgb_image)
for face in faces:
landmarks = predictor(rgb_image, face)
plt.imshow(rgb_image)
for point in landmarks.parts():
plt.plot(point.x, point.y, 'ro')
plt.show()
这个例子展示了如何使用face_landmarks()函数生成图片中人脸的面部特征点,并使用matplotlib库将图片显示出来。你可以将"image.jpg"替换为你自己的图片路径来测试这个例子。
