train a deep learning vehicle detector -凯发k8网页登录
this example shows how to train a vision-based vehicle detector using deep learning.
overview
vehicle detection using computer vision is an important component for tracking vehicles around the ego vehicle. the ability to detect and track vehicles is required for many autonomous driving applications, such as for forward collision warning, adaptive cruise control, and automated lane keeping. automated driving toolbox™ provides pretrained vehicle detectors ( and
) to enable quick prototyping. however, the pretrained models might not suit every application, requiring you to train from scratch. this example shows how to train a vehicle detector from scratch using deep learning.
deep learning is a powerful machine learning technique that you can use to train robust object detectors. several deep learning techniques for object detection exist, including faster r-cnn and you only look once (yolo) v2. this example trains a faster r-cnn vehicle detector using the trainfasterrcnnobjectdetector
function. for more information, see .
download pretrained detector
download a pretrained detector to avoid having to wait for training to complete. if you want to train the detector, set the dotrainingandeval
variable to true.
dotrainingandeval = false; if ~dotrainingandeval && ~exist('fasterrcnnresnet50endtoendvehicleexample.mat','file') disp('downloading pretrained detector (118 mb)...'); pretrainedurl = 'https://www.mathworks.com/supportfiles/vision/data/fasterrcnnresnet50endtoendvehicleexample.mat'; websave('fasterrcnnresnet50endtoendvehicleexample.mat',pretrainedurl); end
load dataset
this example uses a small labeled dataset that contains 295 images. many of these images come from the caltech cars 1999 and 2001 data sets, available at the caltech computational vision website, created by pietro perona and used with permission. each image contains one or two labeled instances of a vehicle. a small dataset is useful for exploring the faster r-cnn training procedure, but in practice, more labeled images are needed to train a robust detector. unzip the vehicle images and load the vehicle ground truth data.
unzip vehicledatasetimages.zip data = load('vehicledatasetgroundtruth.mat'); vehicledataset = data.vehicledataset;
the vehicle data is stored in a two-column table, where the first column contains the image file paths and the second column contains the vehicle bounding boxes.
split the data set into a training set for training the detector and a test set for evaluating the detector. select 60% of the data for training. use the rest for evaluation.
rng(0) shuffledidx = randperm(height(vehicledataset)); idx = floor(0.6 * height(vehicledataset)); trainingdatatbl = vehicledataset(shuffledidx(1:idx),:); testdatatbl = vehicledataset(shuffledidx(idx 1:end),:);
use imagedatastore
and boxlabeldatastore
to create datastores for loading the image and label data during training and evaluation.
imdstrain = imagedatastore(trainingdatatbl{:,'imagefilename'}); bldstrain = boxlabeldatastore(trainingdatatbl(:,'vehicle')); imdstest = imagedatastore(testdatatbl{:,'imagefilename'}); bldstest = boxlabeldatastore(testdatatbl(:,'vehicle'));
combine image and box label datastores.
trainingdata = combine(imdstrain,bldstrain); testdata = combine(imdstest,bldstest);
display one of the training images and box labels.
data = read(trainingdata);
i = data{1};
bbox = data{2};
annotatedimage = insertshape(i,'rectangle',bbox);
annotatedimage = imresize(annotatedimage,2);
figure
imshow(annotatedimage)
create faster r-cnn detection network
a faster r-cnn object detection network is composed of a feature extraction network followed by two subnetworks. the feature extraction network is typically a pretrained cnn, such as resnet-50 or inception v3. the first subnetwork following the feature extraction network is a region proposal network (rpn) trained to generate object proposals - areas in the image where objects are likely to exist. the second subnetwork is trained to predict the actual class of each object proposal.
the feature extraction network is typically a pretrained cnn (for details, see pretrained deep neural networks (deep learning toolbox)). this example uses resnet-50 for feature extraction. you can also use other pretrained networks such as mobilenet v2 or resnet-18, depending on your application requirements.
use fasterrcnnlayers
to create a faster r-cnn network automatically given a pretrained feature extraction network. fasterrcnnlayers
requires you to specify several inputs that parameterize a faster r-cnn network:
network input size
anchor boxes
feature extraction network
first, specify the network input size. when choosing the network input size, consider the minimum size required to run the network itself, the size of the training images, and the computational cost incurred by processing data at the selected size. when feasible, choose a network input size that is close to the size of the training image and larger than the input size required for the network. to reduce the computational cost of running the example, specify a network input size of [224 224 3], which is the minimum size required to run the network.
inputsize = [224 224 3];
note that the training images used in this example are bigger than 224-by-224 and vary in size, so you must resize the images in a preprocessing step prior to training.
next, use estimateanchorboxes
to estimate anchor boxes based on the size of objects in the training data. to account for the resizing of the images prior to training, resize the training data for estimating anchor boxes. use transform
to preprocess the training data, then define the number of anchor boxes and estimate the anchor boxes.
preprocessedtrainingdata = transform(trainingdata, @(data)preprocessdata(data,inputsize)); numanchors = 4; anchorboxes = estimateanchorboxes(preprocessedtrainingdata,numanchors)
anchorboxes = 4×2
96 91
68 65
150 125
38 29
for more information on choosing anchor boxes, see (computer vision toolbox™) and .
now, use resnet50
to load a pretrained resnet-50 model.
featureextractionnetwork = resnet50;
select 'activation_40_relu'
as the feature extraction layer. this feature extraction layer outputs feature maps that are downsampled by a factor of 16. this amount of downsampling is a good trade-off between spatial resolution and the strength of the extracted features, as features extracted further down the network encode stronger image features at the cost of spatial resolution. choosing the optimal feature extraction layer requires empirical analysis. you can use analyzenetwork
to find the names of other potential feature extraction layers within a network.
featurelayer = 'activation_40_relu';
define the number of classes to detect.
numclasses = width(vehicledataset)-1;
create the faster r-cnn object detection network.
lgraph = fasterrcnnlayers(inputsize,numclasses,anchorboxes,featureextractionnetwork,featurelayer);
you can visualize the network using analyzenetwork
or deep network designer from deep learning toolbox™.
if more control is required over the faster r-cnn network architecture, use deep network designer to design the faster r-cnn detection network manually. for more information, see .
data augmentation
data augmentation is used to improve network accuracy by randomly transforming the original data during training. by using data augmentation, you can add more variety to the training data without actually having to increase the number of labeled training samples.
use transform
to augment the training data by randomly flipping the image and associated box labels horizontally. note that data augmentation is not applied to test data. ideally, test data is representative of the original data and is left unmodified for unbiased evaluation.
augmentedtrainingdata = transform(trainingdata,@augmentdata);
read the same image multiple times and display the augmented training data.
augmenteddata = cell(4,1); for k = 1:4 data = read(augmentedtrainingdata); augmenteddata{k} = insertshape(data{1},'rectangle',data{2}); reset(augmentedtrainingdata); end figure montage(augmenteddata,'bordersize',10)
preprocess training data
preprocess the augmented training data to prepare for training.
trainingdata = transform(augmentedtrainingdata,@(data)preprocessdata(data,inputsize));
read the preprocessed data.
data = read(trainingdata);
display the image and box bounding boxes.
i = data{1};
bbox = data{2};
annotatedimage = insertshape(i,'rectangle',bbox);
annotatedimage = imresize(annotatedimage,2);
figure
imshow(annotatedimage)
train faster r-cnn
use trainingoptions
to specify network training options. set 'checkpointpath'
to a temporary location. this enables the saving of partially trained detectors during the training process. if training is interrupted, such as by a power outage or system failure, you can resume training from the saved checkpoint.
options = trainingoptions('sgdm',... 'maxepochs',7,... 'minibatchsize',1,... 'initiallearnrate',1e-3,... 'checkpointpath',tempdir);
use trainfasterrcnnobjectdetector
to train faster r-cnn object detector if dotrainingandeval
is true. otherwise, load the pretrained network.
if dotrainingandeval % train the faster r-cnn detector. % * adjust negativeoverlaprange and positiveoverlaprange to ensure % that training samples tightly overlap with ground truth. [detector, info] = trainfasterrcnnobjectdetector(trainingdata,lgraph,options, ... 'negativeoverlaprange',[0 0.3], ... 'positiveoverlaprange',[0.6 1]); else % load pretrained detector for the example. pretrained = load('fasterrcnnresnet50endtoendvehicleexample.mat'); detector = pretrained.detector; end
this example was verified on an nvidia(tm) titan x gpu with 12 gb of memory. training the network took approximately 20 minutes. the training time varies depending on the hardware you use.
as a quick check, run the detector on one test image. make sure you resize the image to the same size as the training images.
i = imread(testdatatbl.imagefilename{1}); i = imresize(i,inputsize(1:2)); [bboxes,scores] = detect(detector,i);
display the results.
i = insertobjectannotation(i,'rectangle',bboxes,scores);
figure
imshow(i)
evaluate detector using test set
evaluate the trained object detector on a large set of images to measure the performance. computer vision toolbox™ provides object detector evaluation functions to measure common metrics such as average precision (evaluatedetectionprecision
) and log-average miss rates (evaluatedetectionmissrate
). for this example, use the average precision metric to evaluate performance. the average precision provides a single number that incorporates the ability of the detector to make correct classifications (precision) and the ability of the detector to find all relevant objects (recall).
apply the same preprocessing transform to the test data as for the training data.
testdata = transform(testdata,@(data)preprocessdata(data,inputsize));
run the detector on all the test images.
if dotrainingandeval detectionresults = detect(detector,testdata,'minibatchsize',4); else % load pretrained detector for the example. pretrained = load('fasterrcnnresnet50endtoendvehicleexample.mat'); detectionresults = pretrained.detectionresults; end
evaluate the object detector using the average precision metric.
[ap, recall, precision] = evaluatedetectionprecision(detectionresults,testdata);
the precision/recall (pr) curve highlights how precise a detector is at varying levels of recall. the ideal precision is 1 at all recall levels. the use of more data can help improve the average precision but might require more training time. plot the pr curve.
figure plot(recall,precision) xlabel('recall') ylabel('precision') grid on title(sprintf('average precision = %.2f', ap))
supporting functions
function data = augmentdata(data) % randomly flip images and bounding boxes horizontally. tform = randomaffine2d('xreflection',true); sz = size(data{1},[1 2]); rout = affineoutputview(sz, tform); data{1} = imwarp(data{1},tform,'outputview',rout); % sanitize boxes, if needed. this helper function is attached as a % supporting file. open the example in matlab to open this function. data{2} = helpersanitizeboxes(data{2}); % warp boxes. data{2} = bboxwarp(data{2},tform,rout); end function data = preprocessdata(data,targetsize) % resize image and bounding boxes to targetsize. sz = size(data{1},[1 2]); scale = targetsize(1:2)./sz; data{1} = imresize(data{1},targetsize(1:2)); % sanitize boxes, if needed. this helper function is attached as a % supporting file. open the example in matlab to open this function. data{2} = helpersanitizeboxes(data{2}); % resize boxes. data{2} = bboxresize(data{2},scale); end
references
[1] ren, s., k. he, r. gershick, and j. sun. "faster r-cnn: towards real-time object detection with region proposal networks." ieee transactions of pattern analysis and machine intelligence. vol. 39, issue 6, june 2017, pp. 1137-1149.
[2] girshick, r., j. donahue, t. darrell, and j. malik. "rich feature hierarchies for accurate object detection and semantic segmentation." proceedings of the 2014 ieee conference on computer vision and pattern recognition. columbus, oh, june 2014, pp. 580-587.
[3] girshick, r. "fast r-cnn." proceedings of the 2015 ieee international conference on computer vision. santiago, chile, dec. 2015, pp. 1440-1448.
[4] zitnick, c. l., and p. dollar. "edge boxes: locating object proposals from edges." european conference on computer vision. zurich, switzerland, sept. 2014, pp. 391-405.
[5] uijlings, j. r. r., k. e. a. van de sande, t. gevers, and a. w. m. smeulders. "selective search for object recognition." international journal of computer vision. vol. 104, number 2, sept. 2013, pp. 154-171.
see also
functions
- | |