MATLAB: How to cut out an area that I’ve created a boundary to

Image Processing Toolboxmatlab extraction boundaries thresholding

I've created a boundary around the lungs in this image & I would like to show just the area inside the boundar. How would I do this?
I've tried subracting it from the original image but had no luck. Any help would be greatly appreciated.
this is the code so far
I = imread('Image1.png'); %%Read in image
C = I(90:400,40:460); %%Crop out unnecessary parts
thresholded = C < 150; %%Threshold to isolate lung tissue
clearThresh = imclearborder(thresholded); %%Remove artifacts attached to border
BW = bwareaopen(clearThresh,100); %%Remove objects less than 40 pixels in size
dim = size(BW); %%Boundary trace one of the lungs
col = round(dim(2)/2)-130;
row = find(BW(:,col), 1 );
boundary = bwtraceboundary(BW,[row ,col],'N');
imshow(C) %%Display Boundary on original image
hold on;
plot(boundary(:,2),boundary(:,1),'r','LineWidth',3);
BW_filled = imfill(BW,'holes'); %%Boundary Trace the second lung
boundaries = bwboundaries(BW_filled);
for k = 1:2
b = boundaries{k};
plot(b(:,2),b(:,1),'g','LineWidth',3);
end

Best Answer

Close. Here, try this:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
format longg;
format compact;
fontSize = 20;
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
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')
% User said No, so exit.
return;
end
end
% Read in a demo image.
folder = 'C:\Users\Student\Documents\Temporary';
baseFileName = '2z3nja1.jpg';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = rgb2gray(imread(fullFileName));
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows columns numberOfColorBands] = size(grayImage);
% Display the original gray scale image.
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.

set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.

set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Let's compute and display the histogram.
[pixelCount grayLevels] = imhist(grayImage);
subplot(2, 2, 2);
bar(pixelCount);
grid on;
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.
% Find border and mask it off
binaryImage = grayImage == 255;
% Display the image.



subplot(2, 2, 3);
imshow(binaryImage, []);
title('Original Binary Image', 'FontSize', fontSize);
% Get just hte border pixels.
borderImage = logical(binaryImage - imclearborder(binaryImage));
% Move the outer edge in a little bit.
borderImage = imdilate(borderImage, true(7));
% Display the image.
subplot(2, 2, 4);
imshow(borderImage, []);
title('Border Pixels Image', 'FontSize', fontSize);
% Start a new figure.
figure;
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
% Erase border pixels.
grayImage(borderImage) = 0;
% Display the image.
subplot(2, 2, 1);
imshow(grayImage, []);
title('Masked Image', 'FontSize', fontSize);
% Threshold for dark pixels.
binaryImage3 = (grayImage > 0) & (grayImage < 125); % Threshold to isolate lung tissue
% Get the two largest blobs.
[labeledImage numberOfBlobs] = bwlabel(binaryImage3);
blobMeasurements = regionprops(labeledImage, 'Area');
allAreas = [blobMeasurements.Area];
[sortedAreas sortIndices] = sort(allAreas, 'descend');
% Get a list of the blobs that meet our criteria and we need to keep.
keeperIndexes = [sortIndices(1), sortIndices(2)];
% Extract only those blobs that meet our criteria, and
% eliminate those blobs that don't meet our criteria.
% Note how we use ismember() to do this.
keeperBlobsImage = ismember(labeledImage, keeperIndexes);
% Binarize and fill holes.
binaryImage3 = imfill(keeperBlobsImage>0, 'holes');
% Display the image.
subplot(2, 2, 2);
imshow(binaryImage3, []);
title('Two Largest Regions', 'FontSize', fontSize);
% Re-label with only the keeper blobs kept.
labeledImage = bwlabel(keeperBlobsImage, 8); % Label each blob so we can make measurements of it
% Find outer boundaries and trace over image.
% bwboundaries() returns a cell array, where each cell contains the row/column coordinates for an object in the image.
% Plot the borders of two largest regions returned by bwboundaries.
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;
% Now let's extract out just the lungs.
maskedImage = zeros(rows, columns, 'uint8'); % Initialize.
maskedImage(binaryImage3) = grayImage(binaryImage3);
subplot(2, 2, 4);
imshow(maskedImage, []);
title('Lungs Masked', 'FontSize', fontSize);