main content

code generation for semantic segmentation network that uses u-凯发k8网页登录

this example shows code generation for an image segmentation application that uses deep learning. it uses the codegen command to generate a mex function that performs prediction on a dag network object for u-net, a deep learning network for image segmentation.

for a similar example covering segmentation of images by using u-net without the codegen command, see (image processing toolbox).

third-party prerequisites

required

this example generates cuda mex and has the following third-party requirements.

  • cuda® enabled nvidia® gpu and compatible driver.

optional

for non-mex builds such as static, dynamic libraries or executables, this example has the following additional requirements.

  • nvidia toolkit.

  • nvidia cudnn library.

  • environment variables for the compilers and libraries. for more information, see third-party hardware and .

verify gpu environment

use the function to verify that the compilers and libraries necessary for running this example are set up correctly.

envcfg = coder.gpuenvconfig('host');
envcfg.deeplibtarget = 'cudnn';
envcfg.deepcodegen = 1;
envcfg.quiet = 1;
coder.checkgpuinstall(envcfg);

segmentation network

u-net [1] is a type of convolutional neural network (cnn) designed for semantic image segmentation. in u-net, the initial series of convolutional layers are interspersed with max pooling layers, successively decreasing the resolution of the input image. these layers are followed by a series of convolutional layers interspersed with upsampling operators, successively increasing the resolution of the input image. combining these two series paths forms a u-shaped graph. the network was originally trained for and used to perform prediction on biomedical image segmentation applications. this example demonstrates the ability of the network to track changes in forest cover over time. environmental agencies track deforestation to assess and qualify the environmental and ecological health of a region.

deep-learning-based semantic segmentation can yield a precise measurement of vegetation cover from high-resolution aerial photographs. one challenge is differentiating classes that have similar visual characteristics, such as trying to classify a green pixel as grass, shrubbery, or tree. to increase classification accuracy, some data sets contain multispectral images that provide additional information about each pixel. for example, the hamlin beach state park data set supplements the color images with near-infrared channels that provide a clearer separation of the classes.

this example uses the hamlin beach state park data [2] along with a pretrained u-net network in order to correctly classify each pixel.

the u-net used is trained to segment pixels belonging to 18 classes which includes:

0. other class/image border      7. picnic table         14. grass
1. road markings                 8. black wood panel     15. sand
2. tree                          9. white wood panel     16. water (lake)
3. building                     10. orange landing pad   17. water (pond)
4. vehicle (car, truck, or bus) 11. water buoy           18. asphalt (parking lot/walkway)
5. person                       12. rocks
6. lifeguard chair              13. other vegetation

the segmentimageunet entry-point function

the segmentimageunet.m entry-point function performs patchwise semantic segmentation on the input image by using the multispectralunet network found in the multispectralunet.mat file. the function loads the network object from the multispectralunet.mat file into a persistent variable mynet and reuses the persistent variable on subsequent prediction calls.

type('segmentimageunet.m')

get pretrained u-net network

this example uses the multispectralunet mat-file containing the pretrained u-net network. this file is approximately 117 mb in size. download the file from the mathworks website.

trainedunetfile = matlab.internal.examples.downloadsupportfile('vision/data','multispectralunet.mat');

u-net is a dag network that contains 58 layers including convolution, max pooling, depth concatenation, and the pixel classification output layers.

load(trainedunetfile);
disp(net)
  dagnetwork with properties:
         layers: [58×1 nnet.cnn.layer.layer]
    connections: [61×2 table]
     inputnames: {'imageinputlayer'}
    outputnames: {'segmentation-layer'}

to view the network architecture, use the analyzenetwork (deep learning toolbox) function.

analyzenetwork(net);

prepare data

this example uses the high-resolution multispectral data from [2]. the image set was captured using a drone over the hamlin beach state park, ny. the data contains labeled training, validation, and test sets, with 18 object class labels. the size of the data file is ~3.0 gb.

download the mat-file version of the data set using the downloadhamlinbeachmsidata helper function. this function is attached to the example as a supporting file.

if ~exist(fullfile(pwd,'data'),'dir')
    url = 'https://home.cis.rit.edu/~cnspci/other/data/rit18_data.mat';
    downloadhamlinbeachmsidata(url,pwd "/data/");
end
downloading hamlin beach dataset...
this will take several minutes to download...
done.

load and examine the data in matlab.

load(fullfile(pwd,'data','rit18_data','rit18_data.mat'));
% examine data
whos test_data
  name           size                         bytes  class     attributes
  test_data      7x12446x7654            1333663576  uint16              

the image has seven channels. the rgb color channels are the third, second, and first image channels. the next three channels correspond to the near-infrared bands and highlight different components of the image based on their heat signatures. channel 7 is a mask that indicates the valid segmentation region.

the multispectral image data is arranged as numchannels-by-width-by-height arrays. in matlab, multichannel images are arranged as width-by-height-by-numchannels arrays. to reshape the data so that the channels are in the third dimension, use the helper function, switchchannelstothirdplane.

test_data  = switchchannelstothirdplane(test_data);
% confirm data has the correct structure (channels last).
whos test_data
  name               size                     bytes  class     attributes
  test_data      12446x7654x7            1333663576  uint16              

run mex code generation

to generate cuda code for the segmentimageunet.m entry-point function, create a gpu configuration object for a mex target setting the target language to c . use the function to create a cudnn deep learning configuration object and assign it to the deeplearningconfig property of the gpu code configuration object. run the codegen command specifying an input size of 12446-by-7654-by-7 and a patch size of 1024-by-1024. these values correspond to the entire test_data size. the smaller patch sizes speed up inference. to see how the patches are calculated, see the segmentimageunet entry-point function.

cfg = coder.gpuconfig('mex');
cfg.constantinputs = 'remove';
cfg.targetlang = 'c  ';
cfg.deeplearningconfig = coder.deeplearningconfig('cudnn');
inputargs = {ones(size(test_data),'uint16'),...
    coder.constant([1024 1024]),coder.constant(trainedunetfile)};
codegen -config cfg segmentimageunet -args inputargs -report
code generation successful: view report

run generated mex to predict results for test_data

this segmentimageunet function takes in the data to test (test_data) and a vector containing the dimensions of the patch size to use. take patches of the image, predict the pixels in a particular patch, then combine all the patches together. due to the size of test data (12446-by-7654-by-7), it is easier to process such a large image in patches.

segmentedimage = segmentimageunet_mex(test_data);

to extract only the valid portion of the segmentation, multiply the segmented image by the mask channel of the test data.

segmentedimage = uint8(test_data(:,:,7)~=0) .* segmentedimage;

because the output of the semantic segmentation is noisy, remove the noise and stray pixels by using the medfilt2 function.

segmentedimage = medfilt2(segmentedimage,[5,5]);

display u-net segmented test_data

the following line of code creates a vector of the class names.

classnames = [ "roadmarkings","tree","building","vehicle","person", ...
               "lifeguardchair","picnictable","blackwoodpanel",...
               "whitewoodpanel","orangelandingpad","buoy","rocks",...
               "lowlevelvegetation","grass_lawn","sand_beach",...
               "water_lake","water_pond","asphalt"];

overlay the labels on the segmented rgb test image and add a color bar to the segmentation image.

cmap = jet(numel(classnames));
b = labeloverlay(imadjust(test_data(:,:,[3,2,1]),[0 0.6],[0.1 0.9],0.55),...
    segmentedimage,'transparency',0.8,'colormap',cmap);
figure
imshow(b)
n = numel(classnames);
ticks = 1/(n*2):1/n:1;
colorbar('ticklabels',cellstr(classnames),'ticks',ticks,'ticklength',0,...
    'ticklabelinterpreter','none');
colormap(cmap)
title('segmented image');

references

[1] ronneberger, olaf, philipp fischer, and thomas brox. "u-net: convolutional networks for biomedical image segmentation." arxiv preprint arxiv:1505.04597, 2015.

[2] kemker, r., c. salvaggio, and c. kanan. "high-resolution multispectral dataset for semantic segmentation." corr, abs/1703.01918, 2017.

[3] kemker, ronald, carl salvaggio, and christopher kanan. "algorithms for semantic segmentation of multispectral remote sensing imagery using deep learning." isprs journal of photogrammetry and remote sensing, deep learning rs data, 145 (november 1, 2018): 60-77. https://doi.org/10.1016/j.isprsjprs.2018.04.014.

see also

functions

objects

  • | |

related examples

more about

  • (computer vision toolbox)
网站地图