Matlab GUI: Handling User Data and Images

If you like this post, please visit our sponsors above. Thanks!

matlab

It is often an issue to handle user defined data when working with Matlab GUI. In this tutorial I show how to share user data among functions and how to handle Images.

 

 

 

I assume basic knowledge of Matlab GUI. (Please see the tutorial on GUI basics).

We create a simple GUI where a user can select an image and then press a button to display it.

image

First create a simple GUI with an edit box and two push buttons.

image

The plan of action is to allow the user to select a file when he/she presses the ‘Browse’ button, and show the image when he ‘Show Image’ button is pressed.

Reading Images and Setting User Data

In the ‘Browse’ button call back i add the following code.

   1: % get a file to read 

   2: [FileName, FilePath] = uigetfile({ '*.jpg'; '*.jpeg'; '*.bmp'; '*.gif'; '*.tiff'; '*.png' }, 'Select an Image...');

   3: % set the file name and path to the edit box as well

   4: set(handles.editFilePath, 'String', [FilePath, FileName]);

   5: % read the image

   6: I = imread([FilePath, FileName]);

   7: % set the image in the user data, if this is not done, the image would be

   8: % lost

   9: setappdata(JigsawPuzzle, 'MyImage', I);

  10: % set the file name and path in the user data

  11: setappdata(JigsawPuzzle, 'FileNameAndPath', [FilePath, FileName]);

The last two lines are the most important and need explanation.

setappdata(JigsawPuzzle, ‘MyImage’, I);

The first argument of the ‘setappdata’ is the name of a figure object or any object contained within it that will hold the data as its data object, you could use any control but I use the figure itself to assert the global scope of the variables. The second argument is the name of the data variable. The third argument is the data itself.

The last line sets another variable with filename and path, concatenated together.

PS: You might want to read about uigetfile (Use help uigetfile in Matlab).

I have also added similar code to the edit box.

   1: FilePath = get(handles.editFilePath, 'String');

   2: set(handles.editFilePath, 'String', FilePath);

   3: I = imread(FilePath);

   4: setappdata(JigsawPuzzle, 'MyImage', I);

   5: setappdata(JigsawPuzzle, 'FileNameAndPath', FilePath);

Retrieving User Data and Showing the image

This part is rather simpler. I add the following code to the show image button.

   1: Image = getappdata(JigsawPuzzle, 'MyImage');

   2: figure, imshow(Image);

The  getappdata is similar to get function used to retrieve values for control properties.

Please feel free to leave comments and questions.

If you like this post, please visit our sponsors blow. Thanks!

One Response to “Matlab GUI: Handling User Data and Images”

  1. Ahsun says:

    good work :-)
    keep it up

Leave a Reply