main content

semantic segmentation using deep learning -凯发k8网页登录

this example shows how to segment an image using a semantic segmentation network.

a semantic segmentation network classifies every pixel in an image, resulting in an image that is segmented by class. applications for semantic segmentation include road segmentation for autonomous driving and cancer cell segmentation for medical diagnosis. to learn more, see .

this example first shows you how to segment an image using a pretrained deeplab v3 [1] network, which is one type of convolutional neural network (cnn) designed for semantic image segmentation. other types of networks for semantic segmentation include fully convolutional networks (fcn), segnet, and u-net. then, you can optionally download a dataset to train deeplab v3 network using transfer learning. the training procedure shown here can be applied to other types of semantic segmentation networks.

to illustrate the training procedure, this example uses the [2] from the university of cambridge. this dataset is a collection of images containing street-level views obtained while driving. the dataset provides pixel-level labels for 32 semantic classes including car, pedestrian, and road.

a cuda-capable nvidia™ gpu is highly recommended for running this example. use of a gpu requires parallel computing toolbox™. for information about the supported compute capabilities, see gpu computing requirements (parallel computing toolbox).

download pretrained semantic segmentation network

download a pretrained version of deeplab v3 trained on the camvid dataset.

pretrainedurl = 'https://ssd.mathworks.com/supportfiles/vision/data/deeplabv3plusresnet18camvid.zip';
pretrainedfolder = fullfile(tempdir,'pretrainednetwork');
pretrainednetworkzip = fullfile(pretrainedfolder,'deeplabv3plusresnet18camvid.zip'); 
if ~exist(pretrainednetworkzip,'file')
    mkdir(pretrainedfolder);
    disp('downloading pretrained network (58 mb)...');
    websave(pretrainednetworkzip,pretrainedurl);
end
unzip(pretrainednetworkzip, pretrainedfolder)

load the pretrained network.

pretrainednetwork = fullfile(pretrainedfolder,'deeplabv3plusresnet18camvid.mat');  
data = load(pretrainednetwork);
net = data.net;

list the classes this network is trained to classify.

classes = string(net.layers(end).classes)
classes = 11×1 string
    "sky"
    "building"
    "pole"
    "road"
    "pavement"
    "tree"
    "signsymbol"
    "fence"
    "car"
    "pedestrian"
    "bicyclist"

perform semantic image segmentation

read an image that contains classes the network is trained to classify.

i = imread('highway.png');

resize the image to the input size of the network.

inputsize = net.layers(1).inputsize;
i = imresize(i,inputsize(1:2));

perform semantic segmentation using the semanticseg function and the pretrained network.

c = semanticseg(i,net);

overlay the segmentation results on top of the image with labeloverlay. set the overlay color map to the color map values defined by the camvid dataset [2].

cmap = camvidcolormap;
b = labeloverlay(i,c,'colormap',cmap,'transparency',0.4);
figure
imshow(b)
pixellabelcolorbar(cmap, classes);

although the network is pretrained on images of city driving, it produces a reasonable result on a highway driving scene. to improve the segmentation results, the network should be retrained with additional images that contain highway driving scenes. the remainder of this example shows you how to train a semantic segmentation network using transfer learning.

train a semantic segmentation network

this example trains a deeplab v3 network with weights initialized from a pre-trained resnet-18 network. resnet-18 is an efficient network that is well suited for applications with limited processing resources. other pretrained networks such as mobilenet v2 or resnet-50 can also be used depending on application requirements. for more details, see pretrained deep neural networks (deep learning toolbox).

to get a pretrained resnet-18, install (deep learning toolbox). after installation is complete, run the following code to verify that the installation is correct.

resnet18();

download camvid dataset

download the camvid dataset from the following urls.

imageurl = 'http://web4.cs.ucl.ac.uk/staff/g.brostow/motionsegrecdata/files/701_stillsraw_full.zip';
labelurl = 'http://web4.cs.ucl.ac.uk/staff/g.brostow/motionsegrecdata/data/labeledapproved_full.zip';
 
outputfolder = fullfile(tempdir,'camvid'); 
labelszip = fullfile(outputfolder,'labels.zip');
imageszip = fullfile(outputfolder,'images.zip');
if ~exist(labelszip, 'file') || ~exist(imageszip,'file')   
    mkdir(outputfolder)
       
    disp('downloading 16 mb camvid dataset labels...'); 
    websave(labelszip, labelurl);
    unzip(labelszip, fullfile(outputfolder,'labels'));
    
    disp('downloading 557 mb camvid dataset images...');  
    websave(imageszip, imageurl);       
    unzip(imageszip, fullfile(outputfolder,'images'));    
end

note: download time of the data depends on your internet connection. the commands used above block matlab until the download is complete. alternatively, you can use your web browser to first download the dataset to your local disk. to use the file you downloaded from the web, change the outputfolder variable above to the location of the downloaded file.

load camvid images

use to load camvid images. the imagedatastore enables you to efficiently load a large collection of images on disk.

imgdir = fullfile(outputfolder,'images','701_stillsraw_full');
imds = imagedatastore(imgdir);

display one of the images.

i = readimage(imds,559);
i = histeq(i);
imshow(i)

load camvid pixel-labeled images

use to load camvid pixel label image data. a pixellabeldatastore encapsulates the pixel label data and the label id to a class name mapping.

to make training easier, group the 32 original classes in camvid to 11 classes.

classes = [
    "sky"
    "building"
    "pole"
    "road"
    "pavement"
    "tree"
    "signsymbol"
    "fence"
    "car"
    "pedestrian"
    "bicyclist"
    ];

to reduce 32 classes into 11, multiple classes from the original dataset are grouped together. for example, "car" is a combination of "car", "suvpickuptruck", "truck_bus", "train", and "othermoving". return the grouped label ids by using the supporting function camvidpixellabelids, which is listed at the end of this example.

labelids = camvidpixellabelids();

use the classes and label ids to create the pixellabeldatastore.

labeldir = fullfile(outputfolder,'labels');
pxds = pixellabeldatastore(labeldir,classes,labelids);

read and display one of the pixel-labeled images by overlaying it on top of an image.

c = readimage(pxds,559);
cmap = camvidcolormap;
b = labeloverlay(i,c,'colormap',cmap);
imshow(b)
pixellabelcolorbar(cmap,classes);

areas with no color overlay do not have pixel labels and are not used during training.

analyze dataset statistics

to see the distribution of class labels in the camvid dataset, use . this function counts the number of pixels by class label.

tbl = counteachlabel(pxds)
tbl=11×3 table
         name         pixelcount    imagepixelcount
    ______________    __________    _______________
    {'sky'       }    7.6801e 07      4.8315e 08   
    {'building'  }    1.1737e 08      4.8315e 08   
    {'pole'      }    4.7987e 06      4.8315e 08   
    {'road'      }    1.4054e 08      4.8453e 08   
    {'pavement'  }    3.3614e 07      4.7209e 08   
    {'tree'      }    5.4259e 07       4.479e 08   
    {'signsymbol'}    5.2242e 06      4.6863e 08   
    {'fence'     }    6.9211e 06       2.516e 08   
    {'car'       }    2.4437e 07      4.8315e 08   
    {'pedestrian'}    3.4029e 06      4.4444e 08   
    {'bicyclist' }    2.5912e 06      2.6196e 08   

visualize the pixel counts by class.

frequency = tbl.pixelcount/sum(tbl.pixelcount);
bar(1:numel(classes),frequency)
xticks(1:numel(classes)) 
xticklabels(tbl.name)
xtickangle(45)
ylabel('frequency')

ideally, all classes would have an equal number of observations. however, the classes in camvid are imbalanced, which is a common issue in automotive data-sets of street scenes. such scenes have more sky, building, and road pixels than pedestrian and bicyclist pixels because sky, buildings and roads cover more area in the image. if not handled correctly, this imbalance can be detrimental to the learning process because the learning is biased in favor of the dominant classes. later on in this example, you will use class weighting to handle this issue.

the images in the camvid data set are 720 by 960 in size. image size is chosen such that a large enough batch of images can fit in memory during training on an nvidia™ titan x with 12 gb of memory. you may need to resize the images to smaller sizes if your gpu does not have sufficient memory or reduce the training batch size.

prepare training, validation, and test sets

deeplab v3 is trained using 60% of the images from the dataset. the rest of the images are split evenly in 20% and 20% for validation and testing respectively. the following code randomly splits the image and pixel label data into a training, validation and test set.

[imdstrain, imdsval, imdstest, pxdstrain, pxdsval, pxdstest] = partitioncamviddata(imds,pxds);

the 60/20/20 split results in the following number of training, validation and test images:

numtrainingimages = numel(imdstrain.files)
numtrainingimages = 421
numvalimages = numel(imdsval.files)
numvalimages = 140
numtestingimages = numel(imdstest.files)
numtestingimages = 140

create the network

use the deeplabv3pluslayers function to create a deeplab v3 network based on resnet-18. choosing the best network for your application requires empirical analysis and is another level of hyperparameter tuning. for example, you can experiment with different base networks such as resnet-50 or mobilenet v2, or you can try other semantic segmentation network architectures such as segnet, fully convolutional networks (fcn), or u-net.

% specify the network image size. this is typically the same as the traing image sizes.
imagesize = [720 960 3];
% specify the number of classes.
numclasses = numel(classes);
% create deeplab v3 .
lgraph = deeplabv3pluslayers(imagesize, numclasses, "resnet18");

balance classes using class weighting

as shown earlier, the classes in camvid are not balanced. to improve training, you can use class weighting to balance the classes. use the pixel label counts computed earlier with and calculate the median frequency class weights.

imagefreq = tbl.pixelcount ./ tbl.imagepixelcount;
classweights = median(imagefreq) ./ imagefreq
classweights = 11×1
    0.3182
    0.2082
    5.0924
    0.1744
    0.7103
    0.4175
    4.5371
    1.8386
    1.0000
    6.6059
      ⋮

specify the class weights using a .

pxlayer = pixelclassificationlayer('name','labels','classes',tbl.name,'classweights',classweights);
lgraph = replacelayer(lgraph,"classification",pxlayer);

select training options

the optimization algorithm used for training is stochastic gradient descent with momentum (sgdm). use (deep learning toolbox) to specify the hyper-parameters used for sgdm.

% define validation data.
dsval = combine(imdsval,pxdsval);
% define training options. 
options = trainingoptions('sgdm', ...
    'learnrateschedule','piecewise',...
    'learnratedropperiod',10,...
    'learnratedropfactor',0.3,...
    'momentum',0.9, ...
    'initiallearnrate',1e-3, ...
    'l2regularization',0.005, ...
    'validationdata',dsval,...
    'maxepochs',30, ...
    'minibatchsize',8, ...
    'shuffle','every-epoch', ...
    'checkpointpath', tempdir, ...
    'verbosefrequency',2,...
    'plots','training-progress',...
    'validationpatience', 4);

the learning rate uses a piecewise schedule. the learning rate is reduced by a factor of 0.3 every 10 epochs. this allows the network to learn quickly with a higher initial learning rate, while being able to find a solution close to the local optimum once the learning rate drops.

the network is tested against the validation data every epoch by setting the 'validationdata' parameter. the 'validationpatience' is set to 4 to stop training early when the validation accuracy converges. this prevents the network from overfitting on the training dataset.

a mini-batch size of 8 is used to reduce memory usage while training. you can increase or decrease this value based on the amount of gpu memory you have on your system.

in addition, 'checkpointpath' is set to a temporary location. this name-value pair enables the saving of network checkpoints at the end of every training epoch. if training is interrupted due to a system failure or power outage, you can resume training from the saved checkpoint. make sure that the location specified by 'checkpointpath' has enough space to store the network checkpoints. for example, saving 100 deeplab v3 checkpoints requires ~6 gb of disk space because each checkpoint is 61 mb.

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 increasing the number of labeled training samples. to apply the same random transformation to both image and pixel label data use datastore combine and transform. first, combine imdstrain and pxdstrain.

dstrain = combine(imdstrain, pxdstrain);

next, use datastore transform to apply the desired data augmentation defined in the supporting function augmentimageandlabel. here, random left/right reflection and random x/y translation of /- 10 pixels is used for data augmentation.

xtrans = [-10 10];
ytrans = [-10 10];
dstrain = transform(dstrain, @(data)augmentimageandlabel(data,xtrans,ytrans));

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

start training

start training using (deep learning toolbox) if the dotraining flag is true. otherwise, load a pretrained network.

note: the training was verified on an nvidia™ titan x with 12 gb of gpu memory. if your gpu has less memory, you may run out of memory during training. if this happens, try setting 'minibatchsize' to 1 in trainingoptions, or reducing the network input and resizing the training data. training this network takes about 70 minutes. depending on your gpu hardware, it may take longer.

dotraining = false;
if dotraining    
    [net, info] = trainnetwork(dstrain,lgraph,options);
end

test network on one image

as a quick sanity check, run the trained network on one test image.

i = readimage(imdstest,35);
c = semanticseg(i, net);

display the results.

b = labeloverlay(i,c,'colormap',cmap,'transparency',0.4);
imshow(b)
pixellabelcolorbar(cmap, classes);

compare the results in c with the expected ground truth stored in pxdstest. the green and magenta regions highlight areas where the segmentation results differ from the expected ground truth.

expectedresult = readimage(pxdstest,35);
actual = uint8(c);
expected = uint8(expectedresult);
imshowpair(actual, expected)

visually, the semantic segmentation results overlap well for classes such as road, sky, and building. however, smaller objects like pedestrians and cars are not as accurate. the amount of overlap per class can be measured using the intersection-over-union (iou) metric, also known as the jaccard index. use the function to measure iou.

iou = jaccard(c,expectedresult);
table(classes,iou)
ans=11×2 table
      classes         iou  
    ____________    _______
    "sky"           0.93418
    "building"      0.86604
    "pole"          0.37524
    "road"          0.94517
    "pavement"      0.85422
    "tree"          0.91563
    "signsymbol"    0.62075
    "fence"         0.81075
    "car"           0.71446
    "pedestrian"    0.37249
    "bicyclist"     0.69775

the iou metric confirms the visual results. road, sky, and building classes have high iou scores, while classes such as pedestrian and car have low scores. other common segmentation metrics include the and the contour matching score.

evaluate trained network

to measure accuracy for multiple test images, run on the entire test set. a mini-batch size of 4 is used to reduce memory usage while segmenting images. you can increase or decrease this value based on the amount of gpu memory you have on your system.

pxdsresults = semanticseg(imdstest,net, ...
    'minibatchsize',4, ...
    'writelocation',tempdir, ...
    'verbose',false);

semanticseg returns the results for the test set as a pixellabeldatastore object. the actual pixel label data for each test image in imdstest is written to disk in the location specified by the 'writelocation' parameter. use to measure semantic segmentation metrics on the test set results.

metrics = evaluatesemanticsegmentation(pxdsresults,pxdstest,'verbose',false);

evaluatesemanticsegmentation returns various metrics for the entire dataset, for individual classes, and for each test image. to see the dataset level metrics, inspect metrics.datasetmetrics .

metrics.datasetmetrics
ans=1×5 table
    globalaccuracy    meanaccuracy    meaniou    weightediou    meanbfscore
    ______________    ____________    _______    ___________    ___________
       0.89244           0.8657       0.66347      0.82837        0.69324  

the dataset metrics provide a high-level overview of the network performance. to see the impact each class has on the overall performance, inspect the per-class metrics using metrics.classmetrics.

metrics.classmetrics
ans=11×3 table
                  accuracy      iou      meanbfscore
                  ________    _______    ___________
    sky           0.94272     0.90979      0.90853  
    building      0.81488     0.79161      0.63963  
    pole          0.75997     0.24632      0.58505  
    road          0.93955     0.92638      0.80615  
    pavement      0.90048     0.73874      0.74538  
    tree          0.88173      0.7746      0.72892  
    signsymbol    0.76491     0.42338      0.53707  
    fence         0.83661     0.57442       0.5567  
    car           0.92588     0.79441      0.74331  
    pedestrian    0.86718     0.47077      0.64356  
    bicyclist     0.88881      0.6478      0.59473  

although the overall dataset performance is quite high, the class metrics show that underrepresented classes such as pedestrian, bicyclist, and car are not segmented as well as classes such as road, sky, and building. additional data that includes more samples of the underrepresented classes might help improve the results.

supporting functions

function labelids = camvidpixellabelids()
% return the label ids corresponding to each class.
%
% the camvid dataset has 32 classes. group them into 11 classes following
% the original segnet training methodology [1].
%
% the 11 classes are:
%   "sky" "building", "pole", "road", "pavement", "tree", "signsymbol",
%   "fence", "car", "pedestrian",  and "bicyclist".
%
% camvid pixel label ids are provided as rgb color values. group them into
% 11 classes and return them as a cell array of m-by-3 matrices. the
% original camvid class names are listed alongside each rgb value. note
% that the other/void class are excluded below.
labelids = { ...
    
    % "sky"
    [
    128 128 128; ... % "sky"
    ]
    
    % "building" 
    [
    000 128 064; ... % "bridge"
    128 000 000; ... % "building"
    064 192 000; ... % "wall"
    064 000 064; ... % "tunnel"
    192 000 128; ... % "archway"
    ]
    
    % "pole"
    [
    192 192 128; ... % "column_pole"
    000 000 064; ... % "trafficcone"
    ]
    
    % road
    [
    128 064 128; ... % "road"
    128 000 192; ... % "lanemkgsdriv"
    192 000 064; ... % "lanemkgsnondriv"
    ]
    
    % "pavement"
    [
    000 000 192; ... % "sidewalk" 
    064 192 128; ... % "parkingblock"
    128 128 192; ... % "roadshoulder"
    ]
        
    % "tree"
    [
    128 128 000; ... % "tree"
    192 192 000; ... % "vegetationmisc"
    ]
    
    % "signsymbol"
    [
    192 128 128; ... % "signsymbol"
    128 128 064; ... % "misc_text"
    000 064 064; ... % "trafficlight"
    ]
    
    % "fence"
    [
    064 064 128; ... % "fence"
    ]
    
    % "car"
    [
    064 000 128; ... % "car"
    064 128 192; ... % "suvpickuptruck"
    192 128 192; ... % "truck_bus"
    192 064 128; ... % "train"
    128 064 064; ... % "othermoving"
    ]
    
    % "pedestrian"
    [
    064 064 000; ... % "pedestrian"
    192 128 064; ... % "child"
    064 000 192; ... % "cartluggagepram"
    064 128 064; ... % "animal"
    ]
    
    % "bicyclist"
    [
    000 128 192; ... % "bicyclist"
    192 000 192; ... % "motorcyclescooter"
    ]
    
    };
end
function pixellabelcolorbar(cmap, classnames)
% add a colorbar to the current axis. the colorbar is formatted
% to display the class names with the color.
colormap(gca,cmap)
% add colorbar to current figure.
c = colorbar('peer', gca);
% use class names for tick marks.
c.ticklabels = classnames;
numclasses = size(cmap,1);
% center tick labels.
c.ticks = 1/(numclasses*2):1/numclasses:1;
% remove tick mark.
c.ticklength = 0;
end
function cmap = camvidcolormap()
% define the colormap used by camvid dataset.
cmap = [
    128 128 128   % sky
    128 0 0       % building
    192 192 192   % pole
    128 64 128    % road
    60 40 222     % pavement
    128 128 0     % tree
    192 128 128   % signsymbol
    64 64 128     % fence
    64 0 128      % car
    64 64 0       % pedestrian
    0 128 192     % bicyclist
    ];
% normalize between [0 1].
cmap = cmap ./ 255;
end
function [imdstrain, imdsval, imdstest, pxdstrain, pxdsval, pxdstest] = partitioncamviddata(imds,pxds)
% partition camvid data by randomly selecting 60% of the data for training. the
% rest is used for testing.
    
% set initial random state for example reproducibility.
rng(0); 
numfiles = numel(imds.files);
shuffledindices = randperm(numfiles);
% use 60% of the images for training.
numtrain = round(0.60 * numfiles);
trainingidx = shuffledindices(1:numtrain);
% use 20% of the images for validation
numval = round(0.20 * numfiles);
validx = shuffledindices(numtrain 1:numtrain numval);
% use the rest for testing.
testidx = shuffledindices(numtrain numval 1:end);
% create image datastores for training and test.
trainingimages = imds.files(trainingidx);
valimages = imds.files(validx);
testimages = imds.files(testidx);
imdstrain = imagedatastore(trainingimages);
imdsval = imagedatastore(valimages);
imdstest = imagedatastore(testimages);
% extract class and label ids info.
classes = pxds.classnames;
labelids = camvidpixellabelids();
% create pixel label datastores for training and test.
traininglabels = pxds.files(trainingidx);
vallabels = pxds.files(validx);
testlabels = pxds.files(testidx);
pxdstrain = pixellabeldatastore(traininglabels, classes, labelids);
pxdsval = pixellabeldatastore(vallabels, classes, labelids);
pxdstest = pixellabeldatastore(testlabels, classes, labelids);
end
function data = augmentimageandlabel(data, xtrans, ytrans)
% augment images and pixel label images using random reflection and
% translation.
for i = 1:size(data,1)
    
    tform = randomaffine2d(...
        'xreflection',true,...
        'xtranslation', xtrans, ...
        'ytranslation', ytrans);
    
    % center the view at the center of image in the output space while
    % allowing translation to move the output image out of view.
    rout = affineoutputview(size(data{i,1}), tform, 'boundsstyle', 'centeroutput');
    
    % warp the image and pixel labels using the same transform.
    data{i,1} = imwarp(data{i,1}, tform, 'outputview', rout);
    data{i,2} = imwarp(data{i,2}, tform, 'outputview', rout);
    
end
end

references

[1] chen, liang-chieh et al. “encoder-decoder with atrous separable convolution for semantic image segmentation.” eccv (2018).

[2] brostow, g. j., j. fauqueur, and r. cipolla. "semantic object classes in video: a high-definition ground truth database." pattern recognition letters. vol. 30, issue 2, 2009, pp 88-97.

see also

| | | | | | | (deep learning toolbox) | (deep learning toolbox) | (deep learning toolbox) |

related topics

网站地图