clc;
close all;
imtool close all;
clear;
workspace;
format longg;
format compact;
fontSize = 20;
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
return;
end
end
folder = 'C:\Users\Student\Documents\Temporary';
baseFileName = '2z3nja1.jpg';
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
fullFileName = baseFileName;
if ~exist(fullFileName, 'file')
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = rgb2gray(imread(fullFileName));
[rows columns numberOfColorBands] = size(grayImage);
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
[pixelCount grayLevels] = imhist(grayImage);
subplot(2, 2, 2);
bar(pixelCount);
grid on;
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]);
binaryImage = grayImage == 255;
subplot(2, 2, 3);
imshow(binaryImage, []);
title('Original Binary Image', 'FontSize', fontSize);
borderImage = logical(binaryImage - imclearborder(binaryImage));
borderImage = imdilate(borderImage, true(7));
subplot(2, 2, 4);
imshow(borderImage, []);
title('Border Pixels Image', 'FontSize', fontSize);
figure;
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
grayImage(borderImage) = 0;
subplot(2, 2, 1);
imshow(grayImage, []);
title('Masked Image', 'FontSize', fontSize);
binaryImage3 = (grayImage > 0) & (grayImage < 125);
[labeledImage numberOfBlobs] = bwlabel(binaryImage3);
blobMeasurements = regionprops(labeledImage, 'Area');
allAreas = [blobMeasurements.Area];
[sortedAreas sortIndices] = sort(allAreas, 'descend');
keeperIndexes = [sortIndices(1), sortIndices(2)];
keeperBlobsImage = ismember(labeledImage, keeperIndexes);
binaryImage3 = imfill(keeperBlobsImage>0, 'holes');
subplot(2, 2, 2);
imshow(binaryImage3, []);
title('Two Largest Regions', 'FontSize', fontSize);
labeledImage = bwlabel(keeperBlobsImage, 8);
subplot(2, 2, 3);
imshow(grayImage, []);
title('Outlines, from bwboundaries()', 'FontSize', fontSize);
hold on;
boundaries = bwboundaries(binaryImage3);
numberOfBoundaries = size(boundaries);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), 'g', 'LineWidth', 2);
end
hold off;
maskedImage = zeros(rows, columns, 'uint8');
maskedImage(binaryImage3) = grayImage(binaryImage3);
subplot(2, 2, 4);
imshow(maskedImage, []);
title('Lungs Masked', 'FontSize', fontSize);
Best Answer