本文共 2487 字,大约阅读时间需要 8 分钟。
要使用 Dlib 库训练自己的 68 点人脸特征点检测模型,首先需要一个标注工具。Dlib 提供了 imglab 工具,可以帮助我们快速完成标注工作。以下是使用 imglab 工具的步骤指南:
以下是基于 Dlib 库进行训练的完整代码示例:
import osimport dlib# 定义当前工作目录current_path = os.getcwd()# 设置训练数据的路径faces_path = os.path.join(current_path, "examples/faces")# 初始化训练参数options = dlib.shape_predictor_training_options()options.oversampling_amount = 300 # 增加训练样本量options.nu = 0.05 # 调整正则项系数以防止过拟合options.tree_depth = 2 # 设置树的深度options.be_verbose = True # 启用训练信息日志# 加载训练数据training_xml_path = os.path.join(faces_path, "training_with_face_landmarks.xml")# 开始训练模型dlib.train_shape_predictor(training_xml_path, "predictor.dat", options)# 输出训练结果print("Training accuracy: {}".format(dlib.test_shape_predictor(training_xml_path, "predictor.dat")))
以下是 dlib.train_shape_predictor
函数的核心参数及其作用:
2^tree_depth
。以下是测试训练模型的代码示例:
import osimport cv2import dlib# 定义当前工作目录current_path = os.getcwd()# 设置训练数据的路径faces_path = os.path.join(current_path, "examples/faces")# 加载训练好的模型文件predictor_path = os.path.join(faces_path, "predictor.dat")# 初始化人脸检测器和预测器detector = dlib.get_frontal_face_detector()predictor = dlib.shape_predictor(predictor_path)# 遍历训练集中的所有图片for f in glob.glob(os.path.join(faces_path, "*.jpg")): print("Processing file: {}".format(f)) img = cv2.imread(f) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 检测面部关键点 dets = detector(img_gray, 1) print("Number of faces detected: {}".format(len(dets))) for face in dets: # 画出面部框 cv2.rectangle(img, (face.left(), face.top()), (face.right(), face.bottom()), (0, 255, 0), 3) # 预测面部关键点 shape = predictor(img, face) # 绘制面部关键点 for pt in shape.parts(): cv2.circle(img, (pt.x, pt.y), 2, (255, 0, 0), 1)
_oversampling_amount
和 _nu
,以平衡准确率和过拟合风险。通过以上步骤和代码示例,你可以轻松实现基于 Dlib 库的 68 点人脸特征点检测模型训练和测试。
转载地址:http://sgcu.baihongyu.com/