Python+Dlib+Opencv实现人脸采集并表情判别功能需要分为以下几个步骤:
1. 安装必要的依赖库
在开始进行人脸采集并表情判别功能的实现前,需要确保已经安装以下必要的依赖库:
- Python 3.x
- Dlib
- OpenCV
如果没有安装以上依赖库,需要根据实际情况进行安装。
2. 实现人脸采集功能
在实现人脸采集功能前,需要先使用OpenCV和Dlib库来进行人脸检测和人脸特征点定位,代码如下:
import cv2
import dlib
detector = dlib.get_frontal_face_detector()
predictor_path = 'shape_predictor_68_face_landmarks.dat'
predictor = dlib.shape_predictor(predictor_path)
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
for face in faces:
landmarks = predictor(gray, face)
# 进行人脸采集操作
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
在代码中,cv2.VideoCapture(0)打开了电脑摄像头,并且通过while循环不断读取每一帧图像,使用dlib的get_frontal_face_detector()函数进行人脸检测,使用dlib的shape_predictor()函数进行关键点检测,定位出人脸的区域和68个特征点后,通过具体的代码来进行人脸采集操作。
3. 实现人脸表情识别功能
在实现人脸表情识别功能前,需要先训练出一个表情识别的模型,代码如下:
import dlib
import cv2
import numpy as np
detector = dlib.get_frontal_face_detector()
predictor_path = 'shape_predictor_68_face_landmarks.dat'
predictor = dlib.shape_predictor(predictor_path)
def get_landmarks(im):
rects = detector(im, 1)
if len(rects) > 1:
return 'error'
if len(rects) == 0:
return 'error'
return np.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()])
def annotate_landmarks(im, landmarks):
im = im.copy()
for idx, point in enumerate(landmarks):
pos = (point[0, 0], point[0, 1])
cv2.putText(im, str(idx), pos, fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale=0.4, color=(0, 0, 255))
cv2.circle(im, pos, 3, color=(0, 255, 255))
return im
image = cv2.imread('test.jpg', 1)
landmarks = get_landmarks(image)
image_with_landmarks = annotate_landmarks(image, landmarks)
cv2.imshow('Result', image_with_landmarks)
cv2.waitKey(0)
cv2.destroyAllWindows()
其中,通过OpenCV库调用imread()函数加载图片,使用Dlib库中的get_frontal_face_detector()函数进行人脸检测,使用Dlib库中的shape_predictor()函数进行标志物关键点的检测,最后进行图像标记,并将处理结果用OpenCV显示出来。
示例说明
下面给出两个示例,详细讲解"Python+Dlib+Opencv实现人脸采集并表情判别功能的代码":
示例1:
假设您已经在考场内采集到100张表情图片, 并将这些图片保存到到本地文件夹img文件夹中,然后使用下面的代码将高维特征值文件all_features.npy和对应的标签文件all_labels.npy保存到本地文件夹model中。
import dlib
import numpy as np
import cv2
import os
detector = dlib.get_frontal_face_detector()
face_pose_predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
face_encoder = dlib.face_recognition_model_v1('dlib_face_recognition_resnet_model_v1.dat')
train_folder_path = './img'
model_save_path = './model'
if not os.path.exists(model_save_path):
os.mkdir(model_save_path)
# 加载图像,获取特征向量
def get_image_features(image_path):
image = cv2.imread(image_path)
faces = detector(image, 1)
if len(faces) != 1:
return None
face_rect = faces[0]
pose_landmarks = face_pose_predictor(image, face_rect)
face_descriptor = face_encoder.compute_face_descriptor(image, pose_landmarks)
return np.array(face_descriptor)
def get_train_data():
data = []
labels = []
for cls_dir in os.listdir(train_folder_path):
if not os.path.isdir(os.path.join(train_folder_path, cls_dir)):
continue
for img_file in os.listdir(os.path.join(train_folder_path, cls_dir)):
image_path = os.path.join(train_folder_path, cls_dir, img_file)
features = get_image_features(image_path)
if features is None:
print('跳过图像{}'.format(image_path))
continue
data.append(features)
labels.append(cls_dir)
return np.array(data), np.array(labels)
if __name__ == '__main__':
features, labels = get_train_data()
np.save(os.path.join(model_save_path, 'all_features.npy'), features)
np.save(os.path.join(model_save_path, 'all_labels.npy'), labels)
示例2:
假设您已经成功保存了特征值文件all_features.npy和对应的标签文件all_labels.npy,现在需要使用这些特征值和标签训练一个SVM分类器,对新采集到的人脸图片进行表情判别, 以下是实现代码:
import numpy as np
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
model_save_path = './model'
features = np.load(os.path.join(model_save_path, 'all_features.npy'))
labels = np.load(os.path.join(model_save_path, 'all_labels.npy'))
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
svm = SVC(C=10, kernel='linear', probability=True)
svm.fit(X_train, y_train)
y_pred_train = svm.predict(X_train)
y_pred = svm.predict(X_test)
print('训练集准确率:', accuracy_score(y_train, y_pred_train))
print('测试集准确率:', accuracy_score(y_test, y_pred))
# 在需要表情识别时,先获取特征向量
def get_image_features(image_path):
# 略去代码
return np.array(face_descriptor)
# 然后使用训练好的SVM分类器进行表情识别
svm.predict(get_image_features(image_path))
在示例2中,我们先从all_features.npy和all_labels.npy文件中加载数据,然后使用train_test_split分割训练集和测试集,再使用SVM算法进行训练,最后通过accuracy_score函数计算准确率,以便评估模型的性能。 最后,将特征向量传入分类器,获得该图片的表情分类结果。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python+Dlib+Opencv实现人脸采集并表情判别功能的代码 - Python技术站