classdef SelectAndDisplayImage < matlab.apps.AppBase

    % Properties that correspond to app components
    properties (Access = public)
        UIFigure                     matlab.ui.Figure
        SelectImageButton            matlab.ui.control.Button
        UIAxes                       matlab.ui.control.UIAxes
        FilePathEditFieldLabel       matlab.ui.control.Label
        FilePathEditField            matlab.ui.control.EditField
        AnalyzeImageButton           matlab.ui.control.Button
        UIAxes2                      matlab.ui.control.UIAxes
        PixelAreaEditFieldLabel      matlab.ui.control.Label
        PixelAreaEditField           matlab.ui.control.NumericEditField
        FilterThresholdLabel         matlab.ui.control.Label
        FilterThresholdSlider        matlab.ui.control.Slider
        AxesHistogram                matlab.ui.control.UIAxes
        AreastoExtractDropDownLabel  matlab.ui.control.Label
        AreastoExtractDropDown       matlab.ui.control.DropDown
    end

    
    properties (Access = private)
        I = []; % image file
        threshold = 257; %threshold for binarizing gray intensity
        regionsToExtract = 2;
    end
    

    methods (Access = private)

        % Button pushed function: SelectImageButton
        function SelectImageButtonPushed(app, event)
            clc;
            Dir = 'C:\Users\danie\Downloads\images_004\images'; %define invariate file "prefix"            
            [imageExt, path] =  uigetfile('*.png'); %grab the variable part of the image name
            imageName = [Dir filesep imageExt]; %concatenate invariate and variable straings
            app.I = imread(imageName);          %read the image
            imshow(app.I,'parent',app.UIAxes);  %display the image
            
            app.FilePathEditField.Value = path ; %display file path of where original image came from
        end

        % Button pushed function: AnalyzeImageButton
        function AnalyzeImageButtonPushed(app, event)
            originalImage = app.I;
            originalImage = wiener2(app.I, [5 5]);              %dot-removal filter
            histogram(app.AxesHistogram,app.I, 256);    %display histogram of image
            
            %numberToExtract = 2; 
            a_thresh = originalImage >= app.threshold;    % set this threshold
            labelImage = bwlabel(a_thresh);
            props = regionprops(a_thresh,'all');
            sortedSolidity = sort([props.Solidity], 'descend');

            SB = sortedSolidity(1);

            if SB == 1                    % SB only accept solidity ==1 filter out bones 
            %Lung = ismember(labelImage, sortIndices(1:numberToExtract));
            %binaryImage = Lung > 0.5;  
            %J = imclearborder(originalImage);


            SE  = strel('square',3);
            morphologicalGradient = imsubtract(imdilate(labelImage, SE),imerode(labelImage, SE));
            mask = imbinarize(morphologicalGradient,0.03);
            SE  = strel('square',2);
            mask = imclose(mask, SE);
            mask = imfill(mask,'holes');
            mask = bwareafilt(mask,app.regionsToExtract);            % control number of area show
            notMask = ~mask;
            mask = mask | bwpropfilt(notMask,'Area',[-Inf, 5000 - eps(5000)]);
            %showMaskAsOverlay(0.5,mask,'r');                  % you have to download app/function showMaskAsOverlay 

            BW2 = imfill(labelImage,'holes');
            new_image = BW2 ;
            new_image(~mask) = 0;

            B = bwboundaries(new_image);   % can only accept 2 dimensions
       
       
            imshow(new_image,'parent',app.UIAxes2);
            hold(app.UIAxes2,'on');
            visboundaries(B);
            set(gca,'YDir','reverse');
           
        
         
            lungArea = bwarea(new_image);
          
            app.PixelAreaEditField.Value = lungArea;
            

            end
            
            
            
            
        end

        % Value changed function: FilterThresholdSlider
        function FilterThresholdSliderValueChanged(app, event)
            app.threshold = app.FilterThresholdSlider.Value;
            
        end

        % Callback function
        function AreastoExtractKnobValueChanged(app, event)
            app.numberOfRegions = app.AreastoExtractKnob.Value;
            
        end

        % Value changed function: AreastoExtractDropDown
        function AreastoExtractDropDownValueChanged(app, event)
            stringNumber = app.AreastoExtractDropDown.Value;
            app.regionsToExtract = str2double(stringNumber);            
        end
    end

    % App initialization and construction
    methods (Access = private)

        % Create UIFigure and components
        function createComponents(app)

            % Create UIFigure
            app.UIFigure = uifigure;
            app.UIFigure.Position = [100 100 738 521];
            app.UIFigure.Name = 'UI Figure';

            % Create SelectImageButton
            app.SelectImageButton = uibutton(app.UIFigure, 'push');
            app.SelectImageButton.ButtonPushedFcn = createCallbackFcn(app, @SelectImageButtonPushed, true);
            app.SelectImageButton.Position = [38 362 131 68];
            app.SelectImageButton.Text = 'Select Image';

            % Create UIAxes
            app.UIAxes = uiaxes(app.UIFigure);
            title(app.UIAxes, 'Original Image')
            app.UIAxes.PlotBoxAspectRatio = [1 0.76453488372093 0.76453488372093];
            app.UIAxes.XAxisLocation = 'origin';
            app.UIAxes.XColor = [1 1 1];
            app.UIAxes.XTick = [];
            app.UIAxes.YAxisLocation = 'origin';
            app.UIAxes.YColor = [1 1 1];
            app.UIAxes.YTick = [];
            app.UIAxes.Position = [493 314 227 164];

            % Create FilePathEditFieldLabel
            app.FilePathEditFieldLabel = uilabel(app.UIFigure);
            app.FilePathEditFieldLabel.HorizontalAlignment = 'right';
            app.FilePathEditFieldLabel.Position = [254 73 53 22];
            app.FilePathEditFieldLabel.Text = 'File Path';

            % Create FilePathEditField
            app.FilePathEditField = uieditfield(app.UIFigure, 'text');
            app.FilePathEditField.Editable = 'off';
            app.FilePathEditField.Position = [328 73 112 22];

            % Create AnalyzeImageButton
            app.AnalyzeImageButton = uibutton(app.UIFigure, 'push');
            app.AnalyzeImageButton.ButtonPushedFcn = createCallbackFcn(app, @AnalyzeImageButtonPushed, true);
            app.AnalyzeImageButton.Position = [38 105 131 68];
            app.AnalyzeImageButton.Text = 'Analyze Image';

            % Create UIAxes2
            app.UIAxes2 = uiaxes(app.UIFigure);
            title(app.UIAxes2, 'Analyzed Image')
            app.UIAxes2.XColor = [1 1 1];
            app.UIAxes2.XTick = [];
            app.UIAxes2.YColor = [1 1 1];
            app.UIAxes2.YTick = [];
            app.UIAxes2.Position = [462 33 258 242];

            % Create PixelAreaEditFieldLabel
            app.PixelAreaEditFieldLabel = uilabel(app.UIFigure);
            app.PixelAreaEditFieldLabel.HorizontalAlignment = 'right';
            app.PixelAreaEditFieldLabel.Position = [254 114 60 22];
            app.PixelAreaEditFieldLabel.Text = 'Pixel Area';

            % Create PixelAreaEditField
            app.PixelAreaEditField = uieditfield(app.UIFigure, 'numeric');
            app.PixelAreaEditField.Editable = 'off';
            app.PixelAreaEditField.Position = [328 114 112 22];

            % Create FilterThresholdLabel
            app.FilterThresholdLabel = uilabel(app.UIFigure);
            app.FilterThresholdLabel.HorizontalAlignment = 'right';
            app.FilterThresholdLabel.Position = [18 222 89 22];
            app.FilterThresholdLabel.Text = 'Filter Threshold';

            % Create FilterThresholdSlider
            app.FilterThresholdSlider = uislider(app.UIFigure);
            app.FilterThresholdSlider.Limits = [70 200];
            app.FilterThresholdSlider.ValueChangedFcn = createCallbackFcn(app, @FilterThresholdSliderValueChanged, true);
            app.FilterThresholdSlider.Position = [128 231 279 3];
            app.FilterThresholdSlider.Value = 70;

            % Create AxesHistogram
            app.AxesHistogram = uiaxes(app.UIFigure);
            title(app.AxesHistogram, 'Histogram')
            xlabel(app.AxesHistogram, 'Intensity')
            ylabel(app.AxesHistogram, '# of Occurrences')
            app.AxesHistogram.Position = [194 293 300 185];

            % Create AreastoExtractDropDownLabel
            app.AreastoExtractDropDownLabel = uilabel(app.UIFigure);
            app.AreastoExtractDropDownLabel.HorizontalAlignment = 'right';
            app.AreastoExtractDropDownLabel.Position = [12 272 91 22];
            app.AreastoExtractDropDownLabel.Text = 'Areas to Extract';

            % Create AreastoExtractDropDown
            app.AreastoExtractDropDown = uidropdown(app.UIFigure);
            app.AreastoExtractDropDown.Items = {'1', '2', '3', '4'};
            app.AreastoExtractDropDown.ItemsData = {'1', '2', '3', '4'};
            app.AreastoExtractDropDown.ValueChangedFcn = createCallbackFcn(app, @AreastoExtractDropDownValueChanged, true);
            app.AreastoExtractDropDown.Position = [118 272 100 22];
            app.AreastoExtractDropDown.Value = '1';
        end
    end

    methods (Access = public)

        % Construct app
        function app = SelectAndDisplayImage

            % Create and configure components
            createComponents(app)

            % Register the app with App Designer
            registerApp(app, app.UIFigure)

            if nargout == 0
                clear app
            end
        end

        % Code that executes before app deletion
        function delete(app)

            % Delete UIFigure when app is deleted
            delete(app.UIFigure)
        end
    end
end