close all;clear;clc
dataDir = fullfile(toolboxdir('vision'),'visiondata','triangleImages');
imageDir = fullfile(dataDir,'trainingImages');
imds = imageDatastore(imageDir);
classNames = ["triangle","background"];
labelIDs = [255 0];
labelDir = fullfile(dataDir,'trainingLabels');
pxds = pixelLabelDatastore(labelDir,classNames,labelIDs);
patchds = randomPatchExtractionDatastore(imds,pxds,[8 8], ...
'PatchesPerImage',4);
layers = [
imageInputLayer([8 8 1])
convolution2dLayer(3,64,'Padding',1)
reluLayer()
maxPooling2dLayer(2,'Stride',2)
convolution2dLayer(3,64,'Padding',1)
reluLayer()
transposedConv2dLayer(4,64,'Stride',2,'Cropping',1)
convolution2dLayer(1,2)
softmaxLayer()
pixelClassificationLayer()];
options = trainingOptions('sgdm', ...
'InitialLearnRate',1e-3, ...
'MaxEpochs',10, ...
'Verbose',true);
net = trainNetwork(patchds,layers,options);
[x, y]=meshgrid([1:4],[1:4]);
xg=x(:)*8-7;
yg=y(:)*8-7;
I=read(imds);
S=zeros(32,32,'uint8');
C=categorical(zeros(32,32));
for i=1:numel(yg)
Sp=imcrop(I,[yg(i), xg(i), 7 7]);
S(xg(i):xg(i)+7,yg(i):yg(i)+7)=Sp;
C(xg(i):xg(i)+7,yg(i):yg(i)+7) = semanticseg(Sp, net);
end
figure;imshow(I)
figure;imshow(S)
B = labeloverlay(I,C,'Transparency',0.4);
figure;imshow(B)