You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:无法理解dlib C++库glob关键点坐标采集代码

帮你搞懂用glob + dlib实现关键点坐标采集

Hey there! Let's break this down nice and slow since you're new to Python and figuring out how to use dlib (which is built on C++ under the hood, but we don't need to write any C++ code directly!) with glob to collect facial keypoint coordinates. I'll walk you through every part so it makes sense.

先理清核心逻辑

First, let's map out what we're actually trying to do:

  • Use glob to bulk-find image files (so we don't have to type each image path manually)
  • Use dlib's pre-trained models to detect faces in each image
  • Predict and extract the keypoint coordinates (like eye corners, nose tip, etc.) from each detected face

拆解常见代码示例(逐行解释)

Chances are the code you're looking at looks something like this. Let's go line by line:

import glob
import dlib
import cv2

# 1. 加载dlib的预训练模型
face_detector = dlib.get_frontal_face_detector()
keypoint_predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

# 2. 用glob批量获取所有图片路径(比如当前文件夹下的所有JPG)
image_paths = glob.glob("*.jpg")

# 3. 遍历每张图片
for img_path in image_paths:
    # 用OpenCV读取图片
    img = cv2.imread(img_path)
    # 转为灰度图(dlib的人脸检测器对灰度图效果更好)
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # 在灰度图中检测人脸
    detected_faces = face_detector(gray_img)
    
    # 遍历每一个检测到的人脸
    for face in detected_faces:
        # 预测该人脸的关键点
        landmarks = keypoint_predictor(gray_img, face)
        
        # 提取并存储每个关键点的(x,y)坐标
        keypoint_coords = []
        for point_idx in range(0, 68):
            x = landmarks.part(point_idx).x
            y = landmarks.part(point_idx).y
            keypoint_coords.append((x, y))
        
        # 对坐标做后续处理(打印、保存到文件等)
        print(f"{img_path} 的人脸关键点:{keypoint_coords}")

关键模块解释

  • Glob部分:

    • glob.glob("*.jpg") 会找出当前文件夹下所有后缀为.jpg的文件。如果图片在子文件夹(比如./photos/)里,就用glob.glob("./photos/*.jpg");如果要递归查找所有子文件夹里的图片,加上recursive=True:glob.glob("./**/*.jpg", recursive=True)
    • 把glob理解成一个用通配符(*代表任意字符)找文件的工具就行,不用手动写一堆路径。
  • Dlib模型部分:

    • dlib.get_frontal_face_detector() 加载的是预训练的正脸检测器,它会返回图片中人脸所在的矩形区域。
    • dlib.shape_predictor("xxx.dat") 是关键点预测模型,你需要先下载这个预训练文件(常用的是68点人脸模型,文件名一般是shape_predictor_68_face_landmarks.dat),把它放在代码能找到的路径下(和代码同目录,或者写完整的绝对路径)。
  • 关键点提取部分:

    • landmarks.part(point_idx) 可以访问每个单独的关键点,.x和.y是该点相对于图片的像素坐标(图片左上角是坐标原点)。
    • 68个点对应固定的面部特征(比如0-16号是下颌线,36-41号是左眼轮廓等)。

新手常见困惑解答

  • 为什么要用灰度图? dlib的人脸检测器是基于灰度图训练的,而且灰度图的数据量更小,检测速度会更快。
  • 检测不到人脸怎么办? 检查图片是否清晰、人脸是否是正面;如果需要检测侧脸,可以换成dlib.get_face_detector()这个更通用的检测器。
  • 怎么保存关键点? 可以用Python的csv模块把坐标写入CSV文件,示例代码:
    import csv
    with open("keypoints.csv", "a", newline="") as f:
        writer = csv.writer(f)
        # 一行存图片路径+所有坐标
        writer.writerow([img_path] + [coord for pair in keypoint_coords for coord in pair])
    

调试小技巧

  • 从小规模测试开始:先不用glob,写死一张图片的路径测试,确认dlib能正常检测人脸并输出关键点后,再改成批量处理。
  • 打印中间结果:比如加一行print(f"{img_path} 中检测到 {len(detected_faces)} 张人脸"),确认人脸是否被正确识别。
  • 检查模型路径:如果报错说找不到.dat文件,一定要确认路径写对了,或者把模型文件放在代码同目录下。

内容的提问来源于stack exchange,提问作者Dona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:40:47