保姆级教程:用YOLOv11n-pose模型搞定视频人体姿态估计(附完整Python代码)

张开发
2026/4/4 3:17:41 15 分钟阅读
保姆级教程:用YOLOv11n-pose模型搞定视频人体姿态估计(附完整Python代码)
从零开始掌握YOLOv11n-pose舞蹈视频关键点提取实战指南当看到专业舞者行云流水的动作时你是否好奇过如何用技术解析这些姿态人体姿态估计技术正在改变我们分析动作的方式——从体育训练到医疗康复从安防监控到影视特效。而YOLOv11n-pose作为轻量级模型中的佼佼者让普通开发者也能轻松实现专业级姿态分析。本文将带你用Python代码一步步实现舞蹈视频的关键点提取、可视化与数据保存全流程。1. 环境配置与准备工作在开始前我们需要搭建合适的开发环境。推荐使用Python 3.8-3.10版本这是目前主流深度学习框架最稳定的支持范围。以下是需要安装的核心依赖pip install ultralytics opencv-python pandas numpy注意如果遇到CUDA相关错误请先确认已正确安装对应版本的NVIDIA驱动和CUDA工具包。对于没有独立显卡的用户可以添加--cpu参数强制使用CPU运行但处理速度会显著降低。常见环境问题解决方案报错Unable to find CUDA device检查nvidia-smi命令是否能正常显示GPU信息报错Torch not compiled with CUDA enabled重新安装与CUDA版本匹配的PyTorch视频读取失败安装ffmpegsudo apt install ffmpeg(Linux)或下载预编译版本(Windows)建议的项目目录结构/project_root │── /weights │ └── yolov11n-pose.pt │── /videos │ └── dance_sample.mp4 │── /utils │ └── visualization.py └── pose_estimation.py2. 模型加载与视频处理YOLOv11n-pose的模型文件通常以.pt或.pth为后缀可以从官方仓库或经过验证的第三方源获取。模型加载仅需一行代码但有几个关键细节需要注意import cv2 from ultralytics import YOLO # 模型加载最佳实践 model YOLO(weights/yolov11n-pose.pt) # 相对路径更安全 model.fuse() # 加速推理 model.to(cuda) if torch.cuda.is_available() else model.to(cpu)视频处理环节需要特别注意编解码器兼容性问题。以下是经过验证的视频处理方案def init_video_io(video_path, output_dirresults): cap cv2.VideoCapture(video_path) assert cap.isOpened(), f无法打开视频文件 {video_path} # 获取视频属性 fps cap.get(cv2.CAP_PROP_FPS) width int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # 创建输出目录 os.makedirs(output_dir, exist_okTrue) # 初始化视频写入器 output_path f{output_dir}/{os.path.basename(video_path)} fourcc cv2.VideoWriter_fourcc(*mp4v) # 兼容性最好的编码器 writer cv2.VideoWriter(output_path, fourcc, fps, (width, height)) return cap, writer, (width, height), fps3. 关键点检测与数据处理YOLOv11n-pose默认输出17个关键点对应COCO数据集的人体姿态标注规范。各关键点对应的人体部位如下表所示关键点索引人体部位关键点索引人体部位0鼻子9右脚踝1左眼10右脚跟2右眼11左髋3左耳12右髋4右耳13左膝5左肩14右膝6右肩15左踝7左肘16右踝8右肘关键点数据处理时归一化是保证不同分辨率视频数据一致性的关键步骤def normalize_keypoints(keypoints, frame_size): width, height frame_size normalized [] for kpt in keypoints: x, y, conf kpt if conf 0.5: # 置信度阈值过滤 x_norm round(x / width, 4) y_norm round(y / height, 4) normalized.append((x_norm, y_norm, conf)) return normalized4. 姿态可视化与数据保存高质量的可视化能帮助直观理解模型输出。我们设计了多层次的绘制方案def draw_skeleton(frame, keypoints, connections, kpt_color(0,255,0), skeleton_color(255,0,0)): # 绘制关键点 for x, y, conf in keypoints: if conf 0.5: cv2.circle(frame, (int(x), int(y)), 5, kpt_color, -1) # 绘制骨架连线 for (start, end) in connections: x1, y1, c1 keypoints[start] x2, y2, c2 keypoints[end] if c1 0.5 and c2 0.5: cv2.line(frame, (int(x1), int(y1)), (int(x2), int(y2)), skeleton_color, 2) return frame数据保存环节我们采用Excel和JSON双格式输出满足不同分析需求def save_to_excel(data, filename): df pd.DataFrame([ { frame: item[frame], keypoint_id: idx, x: kpt[0], y: kpt[1], confidence: kpt[2] } for item in data for idx, kpt in enumerate(item[keypoints]) ]) df.to_excel(filename, indexFalse) def save_to_json(data, filename): structured { metadata: { total_frames: len(data), keypoint_count: 17, # COCO标准 normalized: True }, frames: data } with open(filename, w) as f: json.dump(structured, f, indent2)5. 完整流程优化与性能调优将上述模块整合后我们还需要考虑性能优化。以下是经过实测有效的加速技巧批处理预测累积3-5帧后批量预测分辨率调整对大尺寸视频先缩放到640x640处理选择性渲染每N帧渲染一次显示画面优化后的主处理循环def process_video(video_path, model, output_dirresults): cap, writer, frame_size, fps init_video_io(video_path, output_dir) keypoint_data [] batch_size 3 frame_batch [] while cap.isOpened(): ret, frame cap.read() if not ret: break # 预处理 resized_frame cv2.resize(frame, (640, 640)) frame_batch.append(resized_frame) # 批处理预测 if len(frame_batch) batch_size: results model.predict(frame_batch, verboseFalse) for i, res in enumerate(results): if hasattr(res, keypoints): kpts res.keypoints.data.cpu().numpy() norm_kpts normalize_keypoints(kpts[0], frame_size) keypoint_data.append({ frame: current_frame i, keypoints: norm_kpts }) # 渲染当前帧 vis_frame draw_skeleton(frame_batch[i].copy(), kpts[0], SKELETON_CONNECTIONS) writer.write(cv2.resize(vis_frame, frame_size)) frame_batch [] # 处理剩余帧 if frame_batch: results model.predict(frame_batch, verboseFalse) # ...相同处理逻辑... # 保存数据 save_to_excel(keypoint_data, f{output_dir}/keypoints.xlsx) save_to_json(keypoint_data, f{output_dir}/keypoints.json) cap.release() writer.release()6. 高级应用动作分析与可视化获得关键点数据后我们可以进行更深层次的分析。例如计算肢体角度def calculate_joint_angle(a, b, c): 计算三个关键点形成的角度 a, b, c: 归一化坐标点 (x,y) 返回角度值(0-180) ba np.array(a) - np.array(b) bc np.array(c) - np.array(b) cosine np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)) angle np.degrees(np.arccos(np.clip(cosine, -1, 1))) return round(angle, 1)还可以生成动作轨迹图def plot_motion_trajectory(keypoints, joint_index, save_path): x_coords [kpt[joint_index][0] for frame in keypoints for kpt in frame[keypoints]] y_coords [kpt[joint_index][1] for frame in keypoints for kpt in frame[keypoints]] plt.figure(figsize(10,6)) plt.scatter(x_coords, y_coords, crange(len(x_coords)), cmapviridis, alpha0.5) plt.colorbar(labelFrame Index) plt.title(fJoint {joint_index} Motion Trajectory) plt.savefig(save_path) plt.close()在实际舞蹈分析项目中这些可视化技术能帮助教练快速识别动作不规范之处。比如通过对比专业舞者与学员的肩部轨迹图可以直观发现旋转幅度差异。

更多文章