MATLAB: How to find the area of an image and display the output in the GUI

app designerImage Processing ToolboxMATLAB

Hi,
I have created a GUI using the APP DESIGNER in Matlab. When I click the AREA button in the GUI, a value is displayed in the field beside the AREA button. However, problem arises when I click the OPEN button in the GUI. A new image is displayed in the Image Panel but the old value of the Area remains in the GUI. I have to manually change the filename in the code in order for the actual value to be displayed on the GUI. The other buttons work perfectly i.e. when I open a new file, all the previous values are replaced automatically with the new values. Only the AREA button is not working as desired. Please note that the AREA value would be that of the area of the Image on the right side of the Image Panel(app.Image_2.ImageSource or the image file that is generated after the ProcessButtonPushed function is performed.) Any suggestions would be very much appreciated.

classdef Patient5 < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
MiddleEarPanel matlab.ui.container.Panel
ImagePanel matlab.ui.container.Panel
Image_2 matlab.ui.control.Image
Image matlab.ui.control.Image
Image2 matlab.ui.control.Image
InfoPanel matlab.ui.container.Panel
FilenameEditFieldLabel matlab.ui.control.Label
FilenameEditField matlab.ui.control.EditField
OptionPanel matlab.ui.container.Panel
OpenButton matlab.ui.control.Button
ProcessButton matlab.ui.control.Button
IntensityProfileButton matlab.ui.control.Button
AreaButton matlab.ui.control.Button
AverageDensityButton matlab.ui.control.Button
StandardDeviationButton matlab.ui.control.Button
Label_2 matlab.ui.control.Label
EditField_5 matlab.ui.control.EditField
RedEditFieldLabel matlab.ui.control.Label
RedEditField matlab.ui.control.EditField
GreenEditFieldLabel matlab.ui.control.Label
GreenEditField matlab.ui.control.EditField
BlueEditFieldLabel matlab.ui.control.Label
BlueEditField matlab.ui.control.EditField
RedStdEditFieldLabel matlab.ui.control.Label
RedStdEditField matlab.ui.control.EditField
GreenStdEditFieldLabel matlab.ui.control.Label
GreenStdEditField matlab.ui.control.EditField
BlueStdEditFieldLabel matlab.ui.control.Label
BlueStdEditField matlab.ui.control.EditField
end
properties (Access = public)
UIAxes matlab.ui.control.UIAxes
UIaxes matlab.ui.control.UIAxes
end
% Callbacks that handle component events
methods (Access = private)
% Callback function: FilenameEditField, OpenButton
function OpenButtonPushed(app, event)
[filename,filepath] = uigetfile({'*.*;*.jpg;*.png;*.bmp;*.oct'}, 'Select File to Open');
fullname = [filepath, filename];
app.FilenameEditField.Value = "filename";
app.Image.ImageSource = fullname;
app.Image_2.ImageSource = "";
app.EditField_5.Value = "";
app.RedStdEditField.Value = "";
app.GreenStdEditField.Value = "";
app.BlueStdEditField.Value = "";
app.RedEditField.Value = "";
app.GreenEditField.Value = "";
app.BlueEditField.Value = "";
app.FilenameEditField.Value = "";
end
% Button pushed function: IntensityProfileButton
function IntensityProfileButtonPushed(app, event)
I = imread(app.Image.ImageSource);
x=[size(I,2)/2 size(I,2)/2];
y=[0 size(I,1)];
c = improfile(I,x,y);
figure
subplot(2,1,1)
imshow(I)
hold on
plot(x,y,'r')
subplot(2,1,2)
plot(c(:,1,1),'r')
hold on
plot(c(:,1,2),'g')
plot(c(:,1,3),'b')
end
% Image clicked function: Image_2
function Image_2Clicked(app, event)
end
% Button pushed function: ProcessButton
function ProcessButtonPushed(app, event)
img = imread(app.Image.ImageSource);
% get red, green, blue channels

redC = img(:,:,1);
greenC = img(:,:,2);
blueC = img(:,:,3);
% mask where red channel is greater than blue channel and green channel greater than blue channel
mask = redC > blueC & greenC > blueC;
% overlay mask into original image
finalimg = bsxfun(@times, img, cast(mask,class(img)));
app.Image_2.ImageSource = finalimg;
end
% Button pushed function: StandardDeviationButton
function StandardDeviationButtonPushed(app, event)
img = imread(app.Image.ImageSource);
% get red, green, blue channels
redC = img(:,:,1);
greenC = img(:,:,2);
blueC = img(:,:,3);
% % mask where red channel is greater than blue channel and green channel greater than blue channel

mask = redC > blueC & greenC > blueC;
D = std2(redC(mask));
E = std2(greenC(mask));
F = std2(blueC(mask));
s = num2str(D);
t = num2str(E);
u = num2str(F);
app.RedStdEditField.Value = s;
app.GreenStdEditField.Value = t;
app.BlueStdEditField.Value = u;
% % overlay mask into original image

%finalimg = bsxfun(@times, img, cast(mask,class(img)));
% %plotting
% figure
% subplot(1,2,1)
% imshow(img)
% subplot(1,2,2)
% imshow(finalimg)
end
% Callback function: AreaButton, FilenameEditField, Image
function AreaButtonPushed(app, event)
%

%===============================================================================

% Read in a standard MATLAB gray scale demo image.

% folder = 'C:\Users\morteza\Downloads\Matlab\Matlab';
% baseFileName = 'finalimg.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.
% fullFileNameOnSearchPath = baseFileName; % No path this time.
% if ~exist(fullFileNameOnSearchPath, '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
M = imread(app.Image_2.ImageSource);
grayImage = imread(M);
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
% It's not really gray scale like we expected - it's color.
% Convert it to gray scale by taking only the green channel.
grayImage = grayImage(:, :, 2); % Take green channel.
end
% Display the original gray scale image.
% subplot(2, 2, 1);

% imshow(grayImage, []);

% axis on;

% 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 he histogram.
% [pixelCount, grayLevels] = imhist(grayImage);

% subplot(2, 2, 2);

% bar(grayLevels, pixelCount);

% grid on;

% title('Histogram of original image', 'FontSize', fontSize);

% xlim([0 grayLevels(end)]); % Scale x axis manually.

binaryImage = grayImage~= 40;
% % Display the binary image.

% subplot(2, 2, 3);

% imshow(binaryImage, []);

% axis on;
% title('Binary Image', 'FontSize', fontSize);

%
% % Fill the binary image.

% binaryImage = imfill(binaryImage, 'holes');

% % Display the binary image.
% subplot(2, 2, 4);

% imshow(binaryImage, []);
% axis on;
% title('Filled Binary Image', 'FontSize', fontSize);

%
% Calculate the area using bwarea().
area1 = bwarea(binaryImage);
% Calculate the area in pixels using sum()
area2 = sum(binaryImage(:));
% message = sprintf('The area = %.1f, or %d\ndepending on how you want to calculate it', area1, area2);
% uiwait(helpdlg(message));
answer = num2str(area2);
% Value = area2;
app.EditField_5.Value = answer;
% app.EditField_4ValueChanged.Value = num2str(Value);
end
% Callback function

function EditField_4ValueChanged(app, event)
% clc; % Clear the command window.
% close all; % Close all figures (except those of imtool.)
% imtool close all; % Close all imtool figures if you have the Image Processing Toolbox.
% clear; % Erase all existing variables. Or clearvars if you want.
% workspace; % Make sure the workspace panel is showing.
% format long g;
% format compact;
% fontSize = 22;
%
% % 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 standard MATLAB gray scale demo image.
% folder = 'C:\Users\morteza\Downloads\Matlab\Matlab';
% baseFileName = 'M1.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.
% fullFileNameOnSearchPath = baseFileName; % No path this time.
% if ~exist(fullFileNameOnSearchPath, '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 = imread(fullFileName);
% % Get the dimensions of the image.
% % numberOfColorBands should be = 1.
% [rows, columns, numberOfColorBands] = size(grayImage);
% if numberOfColorBands > 1
% % It's not really gray scale like we expected - it's color.
% % Convert it to gray scale by taking only the green channel.
% grayImage = grayImage(:, :, 2); % Take green channel.
% end
% % Display the original gray scale image.
% subplot(2, 2, 1);
% imshow(grayImage, []);
% axis on;
% 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(grayLevels, pixelCount);
% grid on;
% title('Histogram of original image', 'FontSize', fontSize);
% xlim([0 grayLevels(end)]); % Scale x axis manually.
%
% binaryImage = grayImage~= 40;
% % Display the binary image.
% subplot(2, 2, 3);
% imshow(binaryImage, []);
% axis on;
% title('Binary Image', 'FontSize', fontSize);
%
% % Fill the binary image.
% binaryImage = imfill(binaryImage, 'holes');
% % Display the binary image.
% subplot(2, 2, 4);
% imshow(binaryImage, []);
% axis on;
% title('Filled Binary Image', 'FontSize', fontSize);
%
%
%
% % Calculate the area using bwarea().
% area1 = bwarea(binaryImage);
% % Calculate the area in pixels using sum()
% area2 = sum(binaryImage(:));
% % message = sprintf('The area = %.1f, or %d\ndepending on how you want to calculate it', area1, area2);

Best Answer

Answer to first question:
(Summarized from comments under the question) The error is due to improper input to imread(). The expected input is a filename, not image data.
Answer to second question:
The reason you're getting a new figure instead of plotting the image in you app axes is because you're directly creating the new figure in your code by calling figure(). Remove the line that creates a new figure and remove the lines that create new subplots. Instead, specify your UIAxes when you callmby specifying the parent property.
function IntensityProfileButtonPushed(app, event)
I = imread(app.Image.ImageSource);
x=[size(I,2)/2 size(I,2)/2];
y=[0 size(I,1)];
c = improfile(I,x,y);
% figure REMOVE
% subplot(2,1,1) REMOVE
imshow(I,'parent',app.UIAxes1) % Use the correct axes handle

hold(app.UIAxes1,'on') % also specify the axes handle here




plot(app.UIAxes1, x,y,'r') % also specify the axes handle here
%subplot(2,1,2) REMOVE
plot(app.UIAxes2, c(:,1,1),'r') % Use the correct axes handle
hold(app.UIAxes2,'on') % also specify the axes handle here
plot(app.UIAxes2,c(:,1,2),'g') % also specify the axes handle here
plot(app.UIAxes2,c(:,1,3),'b') % also specify the axes handle here
end
Lesson learned: always specify the axis handle when possible.