How to display images in APP DESIGNER?

440 views (last 30 days)
Warid Islam
Warid Islam on 3 Aug 2019
Answered: Warid Islam on 5 Aug 2019
I have an user interface which is shown below. There are couple of sections for displaying images in the Image panel. If I click the OPEN button in the Option Panel, an image is displayed on the left side of the Image Panel which is fine. However, problem arises when I click the PROCESS button in the Option Panel. I want the image to be displayed on the right side of the Image Panel. But the image is being displayed on a separate window which I don't want. Any suggestions would be very much appreciated. Thank you.
classdef Patient4 < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
BrainDemoPanel matlab.ui.container.Panel
ImagePanel matlab.ui.container.Panel
Image_2 matlab.ui.control.Image
Image matlab.ui.control.Image
InfoPanel matlab.ui.container.Panel
PatientNameEditFieldLabel matlab.ui.control.Label
PatientNameEditField 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
FeedbackTextAreaLabel matlab.ui.control.Label
FeedbackTextArea matlab.ui.control.TextArea
AverageDensityButton matlab.ui.control.Button
StandardDeviationButton matlab.ui.control.Button
VolumeoftheliquidButton matlab.ui.control.Button
EditField matlab.ui.control.NumericEditField
EditField_2 matlab.ui.control.NumericEditField
EditField_3 matlab.ui.control.NumericEditField
EditField_4 matlab.ui.control.NumericEditField
EditField_5 matlab.ui.control.NumericEditField
end
properties (Access = public)
UIAxes matlab.ui.control.UIAxes
end
% Callbacks that handle component events
methods (Access = private)
% Button pushed function: OpenButton
function OpenButtonPushed(app, event)
[filename,filepath] = uigetfile({'*.*;*.jpg;*.png;*.bmp;*.oct'}, 'Select File to Open');
fullname = [filepath, filename];
app.Image.ImageSource = fullname;
end
% Button pushed function: IntensityProfileButton
function IntensityProfileButtonPushed(app, event)
I = imread('Intensity1.jpg');
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
% Callback function: AreaButton, Image
function AreaButtonPushed(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(:));
answer = 'area2';
app.FeedbackTextArea.Value = answer;
end
% Button pushed function: ProcessButton
function ProcessButtonPushed(app, event)
img = imread('Intensity1.jpg');
% 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)));
%plotting
imshow(finalimg)
end
% Button pushed function: StandardDeviationButton
function StandardDeviationButtonPushed(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);
% uiwait(helpdlg(message));
standarddeviation = std2(binaryImage(:));
message = sprintf('The standard deviation = %.1f, or %d\ndepending on how you want to calculate it', standarddeviation);
uiwait(helpdlg(message));
answer = 'standarddeviation';
app.FeedbackTextArea.Value = answer;
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure and hide until all components are created
app.UIFigure = uifigure('Visible', 'off');
app.UIFigure.Position = [100 100 1282 808];
app.UIFigure.Name = 'UI Figure';
% Create BrainDemoPanel
app.BrainDemoPanel = uipanel(app.UIFigure);
app.BrainDemoPanel.TitlePosition = 'centertop';
app.BrainDemoPanel.Title = 'Brain Demo';
app.BrainDemoPanel.FontWeight = 'bold';
app.BrainDemoPanel.Position = [11 18 1217 783];
% Create ImagePanel
app.ImagePanel = uipanel(app.BrainDemoPanel);
app.ImagePanel.Title = 'Image Panel';
app.ImagePanel.FontWeight = 'bold';
app.ImagePanel.Position = [288 322 913 390];
% Create Image_2
app.Image_2 = uiimage(app.ImagePanel);
app.Image_2.ImageClickedFcn = createCallbackFcn(app, @Image_2Clicked, true);
app.Image_2.Position = [491 76 356 238];
% Create Image
app.Image = uiimage(app.ImagePanel);
app.Image.ImageClickedFcn = createCallbackFcn(app, @AreaButtonPushed, true);
app.Image.Position = [48 76 436 247];
% Create InfoPanel
app.InfoPanel = uipanel(app.BrainDemoPanel);
app.InfoPanel.Title = 'Info';
app.InfoPanel.FontWeight = 'bold';
app.InfoPanel.Position = [8 685 260 67];
% Create PatientNameEditFieldLabel
app.PatientNameEditFieldLabel = uilabel(app.InfoPanel);
app.PatientNameEditFieldLabel.HorizontalAlignment = 'right';
app.PatientNameEditFieldLabel.FontWeight = 'bold';
app.PatientNameEditFieldLabel.Position = [27 15 82 22];
app.PatientNameEditFieldLabel.Text = 'Patient Name';
% Create PatientNameEditField
app.PatientNameEditField = uieditfield(app.InfoPanel, 'text');
app.PatientNameEditField.Position = [116 15 100 22];
% Create OptionPanel
app.OptionPanel = uipanel(app.BrainDemoPanel);
app.OptionPanel.Title = 'Option Panel';
app.OptionPanel.FontWeight = 'bold';
app.OptionPanel.Position = [9 582 260 88];
% Create OpenButton
app.OpenButton = uibutton(app.OptionPanel, 'push');
app.OpenButton.ButtonPushedFcn = createCallbackFcn(app, @OpenButtonPushed, true);
app.OpenButton.Position = [9 41 100 22];
app.OpenButton.Text = 'Open ';
% Create ProcessButton
app.ProcessButton = uibutton(app.OptionPanel, 'push');
app.ProcessButton.ButtonPushedFcn = createCallbackFcn(app, @ProcessButtonPushed, true);
app.ProcessButton.Position = [119 41 100 22];
app.ProcessButton.Text = 'Process';
% Create IntensityProfileButton
app.IntensityProfileButton = uibutton(app.BrainDemoPanel, 'push');
app.IntensityProfileButton.ButtonPushedFcn = createCallbackFcn(app, @IntensityProfileButtonPushed, true);
app.IntensityProfileButton.Position = [18 416 100 22];
app.IntensityProfileButton.Text = 'Intensity Profile';
% Create AreaButton
app.AreaButton = uibutton(app.BrainDemoPanel, 'push');
app.AreaButton.ButtonPushedFcn = createCallbackFcn(app, @AreaButtonPushed, true);
app.AreaButton.Position = [20 376 100 22];
app.AreaButton.Text = 'Area';
% Create FeedbackTextAreaLabel
app.FeedbackTextAreaLabel = uilabel(app.BrainDemoPanel);
app.FeedbackTextAreaLabel.HorizontalAlignment = 'right';
app.FeedbackTextAreaLabel.Position = [17 258 58 22];
app.FeedbackTextAreaLabel.Text = 'Feedback';
% Create FeedbackTextArea
app.FeedbackTextArea = uitextarea(app.BrainDemoPanel);
app.FeedbackTextArea.Position = [90 222 150 60];
% Create AverageDensityButton
app.AverageDensityButton = uibutton(app.BrainDemoPanel, 'push');
app.AverageDensityButton.Position = [17 458 103 22];
app.AverageDensityButton.Text = 'Average Density';
% Create StandardDeviationButton
app.StandardDeviationButton = uibutton(app.BrainDemoPanel, 'push');
app.StandardDeviationButton.ButtonPushedFcn = createCallbackFcn(app, @StandardDeviationButtonPushed, true);
app.StandardDeviationButton.Position = [7 495 118 22];
app.StandardDeviationButton.Text = 'Standard Deviation';
% Create VolumeoftheliquidButton
app.VolumeoftheliquidButton = uibutton(app.BrainDemoPanel, 'push');
app.VolumeoftheliquidButton.Position = [9 534 120 22];
app.VolumeoftheliquidButton.Text = 'Volume of the liquid';
% Create EditField
app.EditField = uieditfield(app.BrainDemoPanel, 'numeric');
app.EditField.Position = [159 534 100 22];
% Create EditField_2
app.EditField_2 = uieditfield(app.BrainDemoPanel, 'numeric');
app.EditField_2.Position = [159 495 100 22];
% Create EditField_3
app.EditField_3 = uieditfield(app.BrainDemoPanel, 'numeric');
app.EditField_3.Position = [159 458 100 22];
% Create EditField_4
app.EditField_4 = uieditfield(app.BrainDemoPanel, 'numeric');
app.EditField_4.Position = [159 416 100 22];
% Create EditField_5
app.EditField_5 = uieditfield(app.BrainDemoPanel, 'numeric');
app.EditField_5.Position = [159 376 100 22];
% Show the figure after all components are created
app.UIFigure.Visible = 'on';
end
end
% App creation and deletion
methods (Access = public)
% Construct app
function app = Patient4
% Create UIFigure and 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
  2 Comments
Warid Islam
Warid Islam on 4 Aug 2019
Hi Walter,
Thank you for your suggestion. I tried to implement the code above but I am getting repeated errors. My image is still being displayed on a separate window. Please find my code and error message below. Thank you.
function ProcessButtonPushed(app, event)
img = imread('Intensity1.jpg');
% 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)));
f = imshow(finalimg);
ax = axes('Parent',f);
plot(ax);
end
My error message is:
Error using axes
Axes cannot be a child of Image.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 4 Aug 2019
If you want to display your image in a uiimage control, then simply assign the image to the ImageSource property of the control:
app.Image_2.ImageSource = someimage;
Note that the image must be RGB. If the image is greyscale, you need to convert it to RGB by repmat'ing the grey channel.
If you want to display your image in an uiaxes using imshow, then you need to specify the uiaxes as a parent in the call to imshow. You don't have a uiaxes in your app currently, so that option is not available to you:
imshow(someimage, 'Parent', app.someuiaxes)
Looking at your method IntensityProfileButtonPushed, you explicity create a figure:
c = improfile(I,x,y);
figure
so, it's no wonder that your image appear in that figure. The subsequent subplot and imshow all happen in that figure.
  5 Comments
Guillaume
Guillaume on 5 Aug 2019
I'm surprised you don't get any error.
First, these
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;
should never be in a function. The various format... only affect the command line. the close all would close your app figure, hence terminate your app, and the clear would clear all inputs to the function, hence make the app variable no longer accessible within the function.
Plus, as a user of your app, I'd be very upset if just using your app cleared my command window or closed any figure I'd created.
Your app display a dialog window because that's exactly what you ask it to do with
message = sprintf('The area = %.1f, or %d\ndepending on how you want to calculate it', area1, area2);
uiwait(helpdlg(message));
As for the
app.FeedbackTextArea.Value = answer;
not working. Again, you should get an error there since as far as I can AreaEditField5 doesn't exist as a control.
Note that whenever you're repeating the same code across several functions, you should extract that repeated part into its own function.

Sign in to comment.

More Answers (1)

Warid Islam
Warid Islam on 5 Aug 2019
Hi Guillaume,
That solves my problem. You were absolutely spot on in identifying my mistake. Thank you very much for the help.

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!