MATLAB实现YOLO目标检测的代码分享
·
文章目录
以下是MATLAB实现YOLO目标检测的完整代码(以YOLOv4为例),涵盖 数据准备、模型训练、单图检测、实时视频检测全流程,代码可直接运行(需替换路径和参数)。
一、完整代码流程
1. 环境检查与数据集准备
% 检查必要工具箱
requiredToolboxes = {'Deep Learning Toolbox', 'Computer Vision Toolbox'};
for tb = requiredToolboxes
if ~license('test', tb{1})
error(['请安装工具箱:', tb{1}]);
end
end
% 数据集路径(替换为你的数据集文件夹)
datasetPath = fullfile('D:\my_yolo_dataset'); % 包含images文件夹和annotations.xml
annotationFile = fullfile(datasetPath, 'annotations.xml');
imageFolder = fullfile(datasetPath, 'images');
% 加载标注数据(VOC格式)
data = objectDetectorTrainingData(annotationFile);
fprintf('加载完成:%d张图像,类别包括:%s\n', ...
length(data), strjoin(unique([data.boxLabels]), ', '));
2. 数据增强(提升模型泛化能力)
% 定义数据增强器(旋转、缩放、翻转)
augmenter = imageDataAugmenter( ...
'RandRotation', [-10, 10], % 随机旋转±10°
'RandScale', [0.9, 1.1], % 随机缩放0.9~1.1倍
'RandXReflection', true, % 随机水平翻转
'RandTranslation', [10, 10]); % 随机平移±10像素
% 创建增强数据集(输入尺寸与YOLOv4匹配:416×416)
inputSize = [416, 416, 3]; % 宽×高×通道
augmentedData = augmentedImageDatastore(inputSize, data, ...
'DataAugmenter', augmenter, ...
'IncludeImageMetaData', true);
3. 配置YOLOv4模型与训练参数
% 选择预训练模型(YOLOv4-csp:轻量版,适合实时检测)
baseNetwork = 'yolov4-csp';
% 训练参数设置(根据GPU显存调整)
trainingOptions = trainingOptions('sgdm', ...
'MiniBatchSize', 2, ... % 批量大小(8GB显存建议2,16GB可设4)
'MaxEpochs', 15, ... % 训练轮数(数据少则10~15轮)
'InitialLearnRate', 1e-4, ... % 初始学习率
'LearnRateSchedule', 'piecewise', ...
'LearnRateDropFactor', 0.1, ... % 学习率衰减因子
'LearnRateDropPeriod', 5, ... % 每5轮衰减一次
'ValidationData', data(1:5), ... % 验证集(前5张图像)
'ValidationFrequency', 3, ... % 每3轮验证一次
'ExecutionEnvironment', 'gpu', ...% GPU加速(无GPU则设为'cpu')
'Verbose', true, ... % 显示训练日志
'Plots', 'training-progress'); % 实时绘制训练曲线
4. 训练YOLOv4模型
% 开始训练(首次运行会下载预训练权重)
trainedDetector = trainYOLOv4ObjectDetector(augmentedData, baseNetwork, trainingOptions);
% 保存模型(避免重复训练)
save(fullfile(datasetPath, 'yolov4_detector.mat'), 'trainedDetector');
fprintf('模型已保存至:%s\n', fullfile(datasetPath, 'yolov4_detector.mat'));
5. 单张图像检测
% 加载训练好的模型
load(fullfile(datasetPath, 'yolov4_detector.mat'), 'trainedDetector');
% 读取测试图像(替换为你的图像路径)
testImage = imread(fullfile(imageFolder, 'test_image.jpg'));
% 目标检测(返回边界框、置信度、类别)
[bboxes, scores, labels] = detect(trainedDetector, testImage);
% 筛选高置信度结果(保留置信度>0.5的目标)
confidenceThreshold = 0.5;
keepIdx = scores > confidenceThreshold;
bboxes = bboxes(keepIdx, :);
labels = labels(keepIdx);
scores = scores(keepIdx);
% 可视化检测结果
detectedImage = insertObjectAnnotation(testImage, 'rectangle', bboxes, ...
cellstr([labels, arrayfun(@(s) sprintf(' (%.2f)', s), scores, 'UniformOutput', false)]));
figure;
imshow(detectedImage);
title('YOLOv4目标检测结果');
6. 实时视频/摄像头检测
% 加载模型
load(fullfile(datasetPath, 'yolov4_detector.mat'), 'trainedDetector');
% 选择输入源:摄像头(默认索引1)或视频文件
useCamera = true; % true=摄像头,false=视频文件
if useCamera
videoSource = videoinput('winvideo', 1); % Windows摄像头(Linux用'v4l2')
else
videoSource = VideoReader('test_video.mp4'); % 替换为你的视频路径
end
% 实时检测循环
figure;
while true
% 获取一帧图像
if useCamera
frame = getsnapshot(videoSource);
else
if hasFrame(videoSource)
frame = readFrame(videoSource);
else
break; % 视频结束
end
end
% 目标检测
[bboxes, scores, labels] = detect(trainedDetector, frame);
% 筛选高置信度结果
keepIdx = scores > 0.5;
bboxes = bboxes(keepIdx, :);
labels = labels(keepIdx);
% 标注并显示
frameWithDetections = insertObjectAnnotation(frame, 'rectangle', bboxes, labels);
imshow(frameWithDetections);
title('实时YOLOv4检测');
drawnow;
% 按ESC键退出(ASCII码27)
if get(gcf, 'CurrentKey') == char(27)
break;
end
end
% 释放资源
if useCamera
stop(videoSource);
delete(videoSource);
end
close all;
二、使用说明
-
数据集准备:
- 需创建
images文件夹存放图像,用MATLAB的Image Labeler标注并导出annotations.xml(参考前文标注步骤)。 - 替换代码中的
datasetPath为你的数据集路径。
- 需创建
-
参数调整:
MiniBatchSize:根据GPU显存调整(显存不足则减小,如1)。MaxEpochs:数据量少(<100张)时设10~15轮,数据多则设30+。inputSize:YOLOv4推荐416×416或608×608(尺寸越大精度越高,速度越慢)。
-
依赖:
- 需安装MATLAB R2021a及以上版本,以及
Deep Learning Toolbox和Computer Vision Toolbox。 - GPU加速需NVIDIA显卡+CUDA配置(见前文GPU配置教程)。
- 需安装MATLAB R2021a及以上版本,以及
三、常见问题解决
- 模型训练慢:确保GPU正常工作(
gpuDevice命令查看),减小MiniBatchSize。 - 检测精度低:增加数据量、延长训练轮数(
MaxEpochs),或调整数据增强参数。 - 实时检测卡顿:减小
inputSize(如320×320),或使用更轻量的模型(如yolov4-tiny)。
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)