一、核心方法与工具
1. 传统方法:HOG+SVM
原理:
- HOG特征:通过计算图像局部梯度方向直方图描述行人形状
- SVM分类:区分行人与非行人样本
实现步骤:
matlab
% 步骤1:加载数据集(需替换为实际路径)
trainingData = imageDatastore('pedestrian_dataset', 'IncludeSubfolders', true, 'LabelSource', 'foldernames');
% 步骤2:提取HOG特征
cellSize = [8 8];
hogFeatureSize = 36 * 4 * 31; % 根据图像尺寸计算
trainingFeatures = zeros(numel(trainingData.Files), hogFeatureSize);
for i = 1:numel(trainingData.Files)
img = readimage(trainingData, i);
img = im2gray(img);
img = imresize(img, [128 64]);
trainingFeatures(i,:) = extractHOGFeatures(img, 'CellSize', cellSize);
end
% 步骤3:训练SVM分类器
svmModel = fitcsvm(trainingFeatures, trainingData.Labels);
% 步骤4:检测行人
detector = vision.PeopleDetector('ClassificationModel', svmModel);
testImg = imread('test.jpg');
[bboxes, scores] = detect(detector, testImg);
% 步骤5:可视化结果
if ~isempty(bboxes)
detectedImg = insertObjectAnnotation(testImg, 'rectangle', bboxes, scores);
imshow(detectedImg);
else
disp('未检测到行人');
end
2. 深度学习方法:YOLOv2
原理:
- 单阶段检测:直接回归目标位置和类别
- 锚点机制:预定义多尺度检测框提升召回率
实现步骤:
matlab
% 加载预训练YOLOv2模型
net = readnet('yolov2-pretrained.mat');
% 图像预处理
inputImage = imread('test.jpg');
inputBlob = imresize(inputImage, net.Layers(1).InputSize(1:2));
inputBlob = im2double(inputBlob);
inputBlob = cat(4, inputBlob, ones(size(inputBlob,1), size(inputBlob,2), 1));
% 前向传播
[outputBlob, ~] = forward(net, inputBlob);
boxes = outputBlob(:, 1:4);
scores = outputBlob(:, 5);
classes = outputBlob(:, 6);
% 非极大值抑制
[nmsBoxes, nmsScores, nmsClasses] = nms(boxes, scores, 0.5);
% 可视化
figure;
imshow(inputImage);
hold on;
for i = 1:size(nmsBoxes, 1)
bbox = nmsBoxes(i,:);
rectangle('Position', bbox, 'EdgeColor', 'r', 'LineWidth', 2);
end
hold off;
二、性能对比与选型建议
| 方法 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| HOG+SVM | 计算效率高,无需GPU | 对遮挡和光照敏感 | 低分辨率图像、嵌入式设备 |
| YOLOv2 | 实时检测,高精度 | 需预训练模型,计算资源需求高 | 自动驾驶、视频监控 |
| 背景差法 | 简单快速,适合静态背景 | 无法处理动态背景和复杂场景 | 室内监控、简单场景检测 |
三、关键优化策略
-
数据增强
- 随机旋转、缩放、添加噪声提升模型泛化性
matlabaugmentedData = imageDataAugmenter('RandRotation', [-10 10], 'RandScale', [0.8 1.2]); -
多尺度检测
- 图像金字塔处理不同尺寸行人
matlabpyramid = imagePyramid(inputImage, 'ScaleFactor', 1.2, 'NumLevels', 4); -
模型压缩
- 使用TensorRT加速推理
matlabnet = dlquantizer(net, 'ExecutionEnvironment', 'gpu'); quantizedNet = quantize(net);
四、完整工程代码结构
├── dataset/ # 数据集
│ ├── train/ # 训练集
│ └── test/ # 测试集
├── models/ # 预训练模型
│ ├── hog_svm.mat # HOG+SVM模型
│ └── yolov2.mat # YOLOv2模型
├── src/
│ ├── feature_extraction.m # 特征提取
│ ├── train_svm.m # SVM训练
│ └── detect_yolov2.m # YOLOv2检测
└── demo.m # 主程序
五、评估指标与可视化
matlab
% 计算混淆矩阵
C = confusionmat(true_labels, predicted_labels);
% 绘制ROC曲线
[X,Y,T,AUC] = perfcurve(true_labels, scores, 1);
plot(X,Y);
xlabel('False Positive Rate');
ylabel('True Positive Rate');
title(['AUC = ' num2str(AUC)]);
% 实时检测帧率统计
fps = 0.9*fps + 0.1*(1/toc);
disp(['当前帧率: ' num2str(fps, '%.1f') ' FPS']);
六、常见问题解决方案
-
漏检问题 调整检测尺度范围(如0.5-3倍原图尺寸) 增加非极大值抑制的IoU阈值(如从0.5调整至0.3)
-
误检问题 引入颜色特征(HSV空间)二次验证 使用级联分类器(如Viola-Jones框架)
-
实时性优化
- 使用MEX加速C++代码
matlabcodegen -config cfg detect_pedestrian_mex -args {im};
七、扩展应用场景
-
交通流量统计
- 结合卡尔曼滤波跟踪行人轨迹
matlabtracker = vision.KalmanFilter('StateTransitionModel', [1 1; 0 1], 'MeasurementModel', [1 0]); -
异常行为检测
- 基于光流法分析运动模式
matlabflow = opticalFlowLK(im1, im2); magnitude = sqrt(flow.Vx.^2 + flow.Vy.^2); -
多摄像头融合 使用Kalman滤波实现跨摄像头目标关联
八、参考
- 必备工具箱 Computer Vision Toolbox(目标检测函数) Deep Learning Toolbox(YOLO模型训练)
- 代码 行人检测功能 www.youwenfan.com/contentcst/63219.html
- 数据集推荐 INRIA Person Dataset(行人标注数据) Caltech Pedestrian Dataset(复杂场景数据)
- 性能分析工具 MATLAB Profiler(代码耗时分析) Deep Learning Toolbox Model Analyzer(模型复杂度评估)