function Lungs = LungSegment(LungsImage, Thresh)
%% Masking Lungs
grayLungs = rgb2gray(LungsImage); % Converts the 3 dimensional image to 2 dimensions removing unneeded information
Extract = 2; % Sets the variable extract to 2
BWLungs = grayLungs < Thresh; % Sets the threshold of the image which depends on the black and white values of the x-ray
BWLungs = imclearborder(BWLungs);  % Supresses the image borders by reducing intensity
BWLungs = bwareaopen(BWLungs, 1000); % Removes any small white objects with fewer than 1000 pixels from the image

[I, ~] = bwlabel(BWLungs); % Returns label connected objects
props_image = regionprops(I, 'area'); % Finds properties of area for the connected objects
Areas = [props_image.Area]; % A vector of the area of each region in the image 
	if Extract > length(Areas); % If 2 is greater than the length of the amount of areas then set the value to equal amount of areas
		Extract = length(Areas);
	end
	if Extract > 0 % Descend the values if extract is positive
		[~, sortedIndexes] = sort(Areas, 'descend');
    else
		BWLungs = false(size(BWLungs)); % There is nothing to extract and end the code
		return;
    end
    
biggestBlob = ismember(I, sortedIndexes(1:Extract)); % Find the biggest regions with the indexes that were set
BWLungs = biggestBlob > 0; % As long as the region is greater than 0 thats our lungs
BWLungs = imfill(BWLungs, 'holes'); % Fill any holes to ensure a complete image
Lungs = grayLungs; % Sets our original gray image to the variable
Lungs(~BWLungs) = 0; % Set anything that is not the lungs to black
end
