main content

object detection using ssd deep learning -凯发k8网页登录

this example shows how to train a single shot detector (ssd).

overview

deep learning is a powerful machine learning technique that automatically learns image features required for detection tasks. there are several techniques for object detection using deep learning such as faster r-cnn, you only look once (yolo v2), and ssd. this example trains an ssd vehicle detector using the trainssdobjectdetector function. for more information, see (computer vision toolbox).

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 dotraining variable to true.

dotraining = false;
if ~dotraining && ~exist('ssdresnet50vehicleexample_22b.mat','file')
    disp('downloading pretrained detector (44 mb)...');
    pretrainedurl = 'https://www.mathworks.com/supportfiles/vision/data/ssdresnet50vehicleexample_22b.mat';
    websave('ssdresnet50vehicleexample_22b.mat',pretrainedurl);
end

load dataset

this example uses a small vehicle data set that contains 295 images. many of these images come from the caltech cars 1999 and 2001 data sets, created by pietro perona and used with permission. each image contains one or two labeled instances of a vehicle. a small data set is useful for exploring the ssd training procedure, but in practice, more labeled images are needed to train a robust detector.

unzip vehicledatasetimages.zip
data = load('vehicledatasetgroundtruth.mat');
vehicledataset = data.vehicledataset;

the training data is stored in a table. the first column contains the path to the image files. the remaining columns contain the roi labels for vehicles. display the first few rows of the data.

vehicledataset(1:4,:)
ans=4×2 table
              imagefilename                   vehicle     
    _________________________________    _________________
    {'vehicleimages/image_00001.jpg'}    {[220 136 35 28]}
    {'vehicleimages/image_00002.jpg'}    {[175 126 61 45]}
    {'vehicleimages/image_00003.jpg'}    {[108 120 45 33]}
    {'vehicleimages/image_00004.jpg'}    {[124 112 38 36]}

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);
shuffledindices = randperm(height(vehicledataset));
idx = floor(0.6 * length(shuffledindices) );
trainingdata = vehicledataset(shuffledindices(1:idx),:);
testdata = vehicledataset(shuffledindices(idx 1:end),:);

use imagedatastore and boxlabeldatastore to load the image and label data during training and evaluation.

imdstrain = imagedatastore(trainingdata{:,'imagefilename'});
bldstrain = boxlabeldatastore(trainingdata(:,'vehicle'));
imdstest = imagedatastore(testdata{:,'imagefilename'});
bldstest = boxlabeldatastore(testdata(:,'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 a ssd object detection network

use the ssdobjectdetector function to automatically create a ssd object detector. ssdobjectdetector requires you to specify several inputs that parameterize the ssd object detector, including the base network also known as feature extraction network, input size, class names, anchor boxes and detection network sources. use the specific layers from input base network to specify the detection network source. detection network will be automatically connected to input base network by ssdobjectdetector function.

the feature extraction network is typically a pretrained cnn (see pretrained deep neural networks for more details). this example uses resnet-50 for feature extraction. other pretrained networks such as mobilenet v2 or resnet-18 can also be used depending on application requirements. the detection sub-network is a small cnn compared to the feature extraction network and is composed of a few convolutional layers and layers specific to ssd.

net = resnet50();
lgraph = layergraph(net);

when choosing the network input size, consider 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. however, to reduce the computational cost of running this example, the network input size is chosen to be [300 300 3]. during training, trainssdobjectdetector automatically resizes the training images to the network input size.

inputsize = [300 300 3];

define object classes to detect.

classnames = {'vehicle'};

to use the pretrained resnet-50 network as a backbone network, you must do these steps.

step 1: remove the layers in pretrained resnet-50 network present after the "activation_40_relu" layer. this also removes the classification and the fully connected layers.

step 2: add seven convolutional layers after the "activation_40_relu" layer to make the backbone network more robust.

% find layer index of 'activation_40_relu'
idx = find(ismember({lgraph.layers.name},'activation_40_relu'));
% remove all layers after 'activation_40_relu' layer
removedlayers = {lgraph.layers(idx 1:end).name};
ssdlayergraph = removelayers(lgraph,removedlayers);
weightsinitializervalue = 'glorot';
biasinitializervalue = 'zeros';
% append extra layers on top of a base network.
extralayers = [];
% add conv6_1 and corresponding relu
filtersize = 1;
numfilters = 256;
numchannels = 1024;
conv6_1 = convolution2dlayer(filtersize, numfilters, numchannels = numchannels, ...
    name = 'conv6_1', ...
    weightsinitializer = weightsinitializervalue, ...
    biasinitializer = biasinitializervalue);
relu6_1 = relulayer(name = 'relu6_1');
extralayers = [extralayers; conv6_1; relu6_1];
% add conv6_2 and corresponding relu
filtersize = 3;
numfilters = 512;
numchannels = 256;
conv6_2 = convolution2dlayer(filtersize, numfilters, numchannels = numchannels, ...
    padding = isamepadding(filtersize), ...
    stride = [2, 2], ...
    name = 'conv6_2', ...
    weightsinitializer = weightsinitializervalue, ...
    biasinitializer = biasinitializervalue);
relu6_2 = relulayer(name = 'relu6_2');
extralayers = [extralayers; conv6_2; relu6_2];
% add conv7_1 and corresponding relu
filtersize = 1;
numfilters = 128;
numchannels = 512;
conv7_1 = convolution2dlayer(filtersize, numfilters, numchannels = numchannels, ...
    name = 'conv7_1', ...
    weightsinitializer = weightsinitializervalue, ...
    biasinitializer = biasinitializervalue);
relu7_1 = relulayer(name = 'relu7_1');
extralayers = [extralayers; conv7_1; relu7_1];
% add conv7_2 and corresponding relu
filtersize = 3;
numfilters = 256;
numchannels = 128;
conv7_2 = convolution2dlayer(filtersize, numfilters, numchannels = numchannels, ...
    padding = isamepadding(filtersize), ...
    stride = [2, 2], ...
    name = 'conv7_2', ...
    weightsinitializer = weightsinitializervalue, ...
    biasinitializer = biasinitializervalue);
relu7_2 = relulayer(name = 'relu7_2');
extralayers = [extralayers; conv7_2; relu7_2];
% add conv8_1 and corresponding relu
filtersize = 1;
numfilters = 128;
numchannels = 256;
conv8_1 = convolution2dlayer(filtersize, numfilters, numchannels = numchannels, ...
    name = 'conv8_1', ...
    weightsinitializer = weightsinitializervalue, ...
    biasinitializer = biasinitializervalue);
relu8_1 = relulayer(name = 'relu8_1');
extralayers = [extralayers; conv8_1; relu8_1];
% add conv8_2 and corresponding relu
filtersize = 3;
numfilters = 256;
numchannels = 128;
conv8_2 = convolution2dlayer(filtersize, numfilters, numchannels = numchannels, ...
    name = 'conv8_2', ...
    weightsinitializer = weightsinitializervalue, ...
    biasinitializer = biasinitializervalue);
relu8_2 = relulayer(name ='relu8_2');
extralayers = [extralayers; conv8_2; relu8_2];
% add conv9_1 and corresponding relu
filtersize = 1;
numfilters = 128;
numchannels = 256;
conv9_1 = convolution2dlayer(filtersize, numfilters, numchannels = numchannels, ...
    padding = isamepadding(filtersize), ...
    name = 'conv9_1', ...
    weightsinitializer = weightsinitializervalue, ...
    biasinitializer = biasinitializervalue);
relu9_1 = relulayer('name', 'relu9_1');
extralayers = [extralayers; conv9_1; relu9_1];
if ~isempty(extralayers)
    lastlayername = ssdlayergraph.layers(end).name;
    ssdlayergraph = addlayers(ssdlayergraph, extralayers);
    ssdlayergraph = connectlayers(ssdlayergraph, lastlayername, extralayers(1).name);
end

specify the layers name from the network to which detection network source will be added.

detnetworksource = ["activation_22_relu", "activation_40_relu", "relu6_2", "relu7_2", "relu8_2"];

specify the anchor boxes. anchor boxes (m-by-1 cell array) count (m) must be same as detection network source count.

anchorboxes = {[60,30;30,60;60,21;42,30];...
               [111,60;60,111;111,35;64,60;111,42;78,60];...
               [162,111;111,162;162,64;94,111;162,78;115,111];...
               [213,162;162,213;213,94;123,162;213,115;151,162];...
               [264,213;213,264;264,151;187,213]};

create the ssd object detector object.

detector = ssdobjectdetector(ssdlayergraph,classnames,anchorboxes,detectionnetworksource=detnetworksource,inputsize=inputsize,modelname='ssdvehicle'); 

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.

  • randomly scale the image, associated box labels.

  • jitter image color.

note that data augmentation is not applied to the test data. ideally, test data should be representative of the original data and is left unmodified for unbiased evaluation.

augmentedtrainingdata = transform(trainingdata,@augmentdata);

visualize augmented training data by reading the same image multiple times.

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.

preprocessedtrainingdata = transform(augmentedtrainingdata,@(data)preprocessdata(data,inputsize));

read the preprocessed training data.

data = read(preprocessedtrainingdata);

display the image and bounding boxes.

i = data{1};
bbox = data{2};
annotatedimage = insertshape(i,'rectangle',bbox);
annotatedimage = imresize(annotatedimage,2);
figure
imshow(annotatedimage)

train ssd object detector

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', ...
        minibatchsize = 16, ....
        initiallearnrate = 1e-3, ...
        learnrateschedule = 'piecewise', ...
        learnratedropperiod = 30, ...
        learnratedropfactor =  0.8, ...
        maxepochs = 20, ...
        verbosefrequency = 50, ...
        checkpointpath = tempdir, ...
        shuffle = 'every-epoch');

use (computer vision toolbox) function to train ssd object detector if dotraining to true. otherwise, load a pretrained network.

if dotraining
    % train the ssd detector.
    [detector, info] = trainssdobjectdetector(preprocessedtrainingdata,detector,options);
else
    % load pretrained detector for the example.
    pretrained = load('ssdresnet50vehicleexample_22b.mat');
    detector = pretrained.detector;
end

this example is verified on an nvidia™ titan x gpu with 12 gb of memory. if your gpu has less memory, you may run out of memory. if this happens, lower the 'minibatchsize' using the trainingoptions function. training this network took approximately 2 hours using this setup. training time varies depending on the hardware you use.

as a quick test, run the detector on one test image.

data = read(testdata);
i = data{1,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. note that data augmentation is not applied to the test data. test data should be representative of the original data and be left unmodified for unbiased evaluation.

preprocessedtestdata = transform(testdata,@(data)preprocessdata(data,inputsize));

run the detector on all the test images.

detectionresults = detect(detector, preprocessedtestdata, minibatchsize = 32);

evaluate the object detector using average precision metric.

[ap,recall,precision] = evaluatedetectionprecision(detectionresults, preprocessedtestdata);

the precision/recall (pr) curve highlights how precise a detector is at varying levels of recall. ideally, the precision would be 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))

code generation

once the detector is trained and evaluated, you can generate code for the ssdobjectdetector using gpu coder™. for more details, see (computer vision toolbox) example.

supporting functions

function b = augmentdata(a)
% apply random horizontal flipping, and random x/y scaling. boxes that get
% scaled outside the bounds are clipped if the overlap is above 0.25. also,
% jitter image color.
b = cell(size(a));
i = a{1};
sz = size(i);
if numel(sz)==3 && sz(3) == 3
    i = jittercolorhsv(i,...
        contrast = 0.2,...
        hue = 0,...
        saturation = 0.1,...
        brightness = 0.2);
end
% randomly flip and scale image.
tform = randomaffine2d(xreflection = true, scale = [1 1.1]);  
rout = affineoutputview(sz,tform, boundsstyle = 'centeroutput');    
b{1} = imwarp(i,tform,outputview = rout);
% sanitize boxes, if needed. this helper function is attached as a
% supporting file. open the example in matlab to access this function.
a{2} = helpersanitizeboxes(a{2});    
% apply same transform to boxes.
[b{2},indices] = bboxwarp(a{2},tform,rout,overlapthreshold = 0.25);    
b{3} = a{3}(indices);  
% return original data only when all boxes are removed by warping.
if isempty(indices)
    b = a;
end
end
function data = preprocessdata(data,targetsize)
% resize image and bounding boxes to the 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 access this function.
data{2} = helpersanitizeboxes(data{2});
% resize boxes.
data{2} = bboxresize(data{2},scale);
end
function p = isamepadding(filtersize)
    p = floor(filtersize / 2);
end

references

[1] liu, wei, dragomir anguelov, dumitru erhan, christian szegedy, scott reed, cheng yang fu, and alexander c. berg. "ssd: single shot multibox detector." in 14th european conference on computer vision, eccv 2016. springer verlag, 2016.

see also

apps

functions

  • (computer vision toolbox) | | | | (computer vision toolbox) | (computer vision toolbox) | | (computer vision toolbox) |

objects

  • (computer vision toolbox) | (computer vision toolbox) |

related topics

  • (computer vision toolbox)
  • (computer vision toolbox)
  • (computer vision toolbox)
网站地图