1. 手势识别与Light-HaGRID数据集入门第一次接触手势识别项目时我被海量数据需求吓到了。直到发现Light-HaGRID这个轻量数据集才明白原来入门可以这么简单。这个数据集最吸引我的地方在于它把原始716GB的HaGRID数据压缩到18GB同时保留了18种常见手势的核心特征。我实测发现即使是使用普通笔记本电脑的GPU也能流畅完成模型训练。Light-HaGRID包含的手势类型特别实用比如OK、比心、点赞这些生活中常用的手势都有覆盖。数据集已经贴心地做好了两种格式转换VOC格式的XML标注文件可以直接用于目标检测训练而Classification文件夹里的裁剪图片则专门为分类任务准备。记得第一次使用时我直接跳过了繁琐的数据预处理阶段节省了至少三天的工作量。数据集里的每张图片都经过等比例缩小到20万像素这个分辨率在保持识别精度的同时大幅降低了计算资源消耗。我对比过原始高分辨率图片和压缩后的效果在YOLOv5模型上准确率差异不到2%但训练速度提升了近5倍。2. 数据准备与环境配置实战2.1 数据集获取与结构解析下载Light-HaGRID后你会看到这样的目录结构Light-HaGRID/ ├── Annotations/ # VOC格式XML标注文件 ├── JPEGImages/ # 原始图像 └── Classification/ # 裁剪后的手势分类图片我建议先检查数据集完整性。可以运行这个Python脚本快速统计样本数量import os from collections import Counter def check_dataset(root_path): class_counts Counter() xml_dir os.path.join(root_path, Annotations) for xml_file in os.listdir(xml_dir): with open(os.path.join(xml_dir, xml_file)) as f: content f.read() classes [line.split()[1].split()[0] for line in content.split(\n) if name in line] class_counts.update(classes) print(各类别样本分布, class_counts.most_common()) check_dataset(path/to/Light-HaGRID)2.2 训练环境搭建技巧在配置YOLOv5环境时我踩过几个坑值得分享。首先推荐使用Python 3.8版本这是与PyTorch兼容性最好的版本。安装依赖时要注意# 创建conda环境推荐 conda create -n gesture python3.8 conda activate gesture # 安装PyTorch根据CUDA版本选择 pip install torch1.10.0cu113 torchvision0.11.1cu113 -f https://download.pytorch.org/whl/torch_stable.html # 安装YOLOv5 git clone https://github.com/ultralytics/yolov5 cd yolov5 pip install -r requirements.txt如果遇到CUDA out of memory错误可以尝试在train.py中添加这个参数parser.add_argument(--batch-size, typeint, default16) # 显存不足时可减小3. YOLOv5模型训练全流程3.1 数据准备与配置文件修改YOLOv5需要特定的数据集格式。我写了个转换脚本将VOC格式转为YOLO格式import xml.etree.ElementTree as ET import os def convert_voc_to_yolo(xml_path, txt_path, classes): tree ET.parse(xml_path) root tree.getroot() with open(txt_path, w) as f: for obj in root.findall(object): cls obj.find(name).text cls_id classes.index(cls) bbox obj.find(bndbox) xmin float(bbox.find(xmin).text) ymin float(bbox.find(ymin).text) xmax float(bbox.find(xmax).text) ymax float(bbox.find(ymax).text) # 转换坐标 width float(root.find(size).find(width).text) height float(root.find(size).find(height).text) x_center (xmin xmax) / 2 / width y_center (ymin ymax) / 2 / height w (xmax - xmin) / width h (ymax - ymin) / height f.write(f{cls_id} {x_center} {y_center} {w} {h}\n) # 示例调用 classes [call, dislike, fist, four, like, mute, ok, one, palm, peace, rock, stop, three, two_up] convert_voc_to_yolo(example.xml, example.txt, classes)然后在data目录下创建gesture.yaml配置文件# 手势识别数据集配置 train: ../Light-HaGRID/train.txt val: ../Light-HaGRID/val.txt # 类别数 nc: 14 # 类别名称 names: [call, dislike, fist, four, like, mute, ok, one, palm, peace, rock, stop, three, two_up]3.2 模型训练与调优启动训练的命令很简单python train.py --img 640 --batch 16 --epochs 100 --data data/gesture.yaml --cfg models/yolov5s.yaml --weights yolov5s.pt但有几个关键参数需要关注--img 640: 输入图像尺寸越大精度可能越高但速度越慢--batch 16: 批大小根据GPU显存调整--epochs 100: 训练轮数建议至少50轮训练过程中我习惯用TensorBoard监控指标tensorboard --logdir runs/train如果发现过拟合可以尝试增加数据增强参数--augment True使用更大的模型yolov5m.yaml或yolov5l.yaml添加早停机制--patience 104. 多平台部署实战4.1 Python端部署方案训练完成后导出模型为ONNX格式python export.py --weights runs/train/exp/weights/best.pt --include onnx我封装了一个简单的推理类import cv2 import torch import numpy as np class GestureDetector: def __init__(self, model_path): self.model torch.hub.load(ultralytics/yolov5, custom, pathmodel_path) self.classes self.model.names def detect(self, image): results self.model(image) return results.pandas().xyxy[0].to_dict(records) def draw_results(self, image, results): for res in results: label f{self.classes[int(res[class])]} {res[confidence]:.2f} cv2.rectangle(image, (int(res[xmin]), int(res[ymin])), (int(res[xmax]), int(res[ymax])), (0,255,0), 2) cv2.putText(image, label, (int(res[xmin]), int(res[ymin])-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2) return image # 使用示例 detector GestureDetector(best.pt) cap cv2.VideoCapture(0) while True: ret, frame cap.read() results detector.detect(frame) frame detector.draw_results(frame, results) cv2.imshow(Gesture Detection, frame) if cv2.waitKey(1) ord(q): break cap.release()4.2 Android端部署要点Android部署的关键是将模型转换为TFLite格式python export.py --weights best.pt --include tflite在Android项目中需要注意添加TensorFlow Lite依赖implementation org.tensorflow:tensorflow-lite:2.8.0 implementation org.tensorflow:tensorflow-lite-gpu:2.8.0预处理代码要匹配训练时的配置// 图像预处理 public static ByteBuffer convertBitmapToByteBuffer(Bitmap bitmap, int width, int height) { ByteBuffer imgData ByteBuffer.allocateDirect(4 * width * height * 3); imgData.order(ByteOrder.nativeOrder()); int[] intValues new int[width * height]; bitmap.getPixels(intValues, 0, width, 0, 0, width, height); int pixel 0; for (int i 0; i width; i) { for (int j 0; j height; j) { int val intValues[pixel]; imgData.putFloat(((val 16) 0xFF) / 255.0f); // R imgData.putFloat(((val 8) 0xFF) / 255.0f); // G imgData.putFloat((val 0xFF) / 255.0f); // B } } return imgData; }后处理要解析YOLOv5输出// 解析输出 private ListRecognition parseOutput(float[][][] output, float threshold) { ListRecognition recognitions new ArrayList(); for (int i 0; i OUTPUT_WIDTH; i) { float confidence output[0][i][4]; if (confidence threshold) { int classId -1; float maxClass 0; for (int c 0; c NUM_CLASSES; c) { float classScore output[0][i][5 c]; if (classScore maxClass) { classId c; maxClass classScore; } } float score maxClass * confidence; if (score threshold) { float x output[0][i][0]; float y output[0][i][1]; float w output[0][i][2]; float h output[0][i][3]; recognitions.add(new Recognition(classId, labels[classId], score, new RectF(x - w/2, y - h/2, x w/2, y h/2))); } } } return recognitions; }5. 性能优化与常见问题解决在实际部署中我发现几个关键性能瓶颈点。首先是模型大小问题原始YOLOv5s模型在Android上运行帧率只有15FPS左右。通过量化可以显著提升性能python export.py --weights best.pt --include tflite --int8量化后的模型大小减小到原来的1/4在骁龙865上能达到30FPS。但要注意量化可能会损失1-2%的准确率建议在量化后重新评估模型性能。另一个常见问题是手势误识别。我的解决方案是添加时序平滑处理连续3帧检测到相同手势才确认设置区域ROI只关注屏幕特定区域的手势添加距离判断根据检测框大小过滤过远的手势内存泄漏是Android开发中的另一个痛点。建议在Activity销毁时显式释放资源Override protected void onDestroy() { if (tflite ! null) { tflite.close(); tflite null; } super.onDestroy(); }最后分享一个实用技巧在光线条件差的环境下可以添加直方图均衡化预处理# 在Python端 img cv2.cvtColor(img, cv2.COLOR_BGR2YUV) img[:,:,0] cv2.equalizeHist(img[:,:,0]) img cv2.cvtColor(img, cv2.COLOR_YUV2BGR) # 在Android端 public static Bitmap enhanceContrast(Bitmap bitmap) { Mat mat new Mat(); Utils.bitmapToMat(bitmap, mat); Mat yuv new Mat(); Imgproc.cvtColor(mat, yuv, Imgproc.COLOR_RGB2YUV); ListMat channels new ArrayList(); Core.split(yuv, channels); Imgproc.equalizeHist(channels.get(0), channels.get(0)); Core.merge(channels, yuv); Imgproc.cvtColor(yuv, mat, Imgproc.COLOR_YUV2RGB); Bitmap result Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(mat, result); return result; }