Creating a Simple GUI
Goals
In this section of the lab our goal is to create a functioning image manipulation GUI, which will later be appended with new functionality. Our GUI when completed will have the following features:
- A title
- A place to display an image
- A file list with all images in the directory
- A button to read in a given file
- A toggle switch to make the image black and white or color
Some of the information in this portion may be repetitve of the rest of the lab. It is merely a step by step walkthrough however, so if you are comfortable without this tutorial you can find the essentialinformation elsewhere in the lab.
Laying out the GUI
Laying out a GUI in MATLAB is perhaps the easiest part of the whole creation. MATLAB's GUIDE interface is pretty much just drag and drop pieces, it will then write all of the beginning code framework for us. The process can be broken down as follows:
- Navigate to the working directory where you would like to begin GUI development. This is where all files will be saved, and eventually where images will have to be placed in order to be read in to the GUI
- Now we start up guide by typing "guide" (not including the quotes) into our command window. What appears is the following picture:

- In the popup window we will select Blank GUI. We will also check "Save new figure as:" At the end of the path I changed Untitled.fig to test.fig you may call it whatever you like, but for the purpose of this tutorial I called it test.fig
- At this point an m-file will load up, and in front of it the GUIDE interface will also load up (see screenshot below). This is the interface we will use to layout our GUI. Close the m-file, we will get back to that later

- Great! Now let's complete our first goal. We would like to add a title. From the tool listing on the left side of the guide interface select the "Static Text" button. If you now move your cursor to the empty GUI layout it will become crosshairs. Click and drag to specify the region for your static text.
- Our next step is going to be to change the text from "Static Text" to our title, which I called "Image Fun!". To do this, double click on the text field. This will bring up a new window filled with properties for the text. This is called the inspector. Scroll down to where it says "String" and change "Static Test" to a title of your choice, or "Image Fun!".
- Congrats! That's pretty much all there is to layout. Now drag and drop onto the GUI, an "Axes" a "ListBox", a "Push Button", and a "Toggle Button". Arrange them to look basically like the picture below (just the layout, we'll change the rest of it too match later on)
- Finally, we will need to set some of the properties of the elements. Let's start with the "ListBox", double click on the listbox, find the "Tag" property in the inspector and change it to "filelist".
- Next we'll take care of the push button. Change it's "Tag" to "readButton", and the "String" to "Read".
- The last modification we need to make is to the toggle button. Change its "String" to "B/W Color", its "Tag" to "BWtoggle", and lastly, we don't want this button to work unless there is an image to modify so change the "Enable" property to "Off".
Congratulations!!! That is all for the layout of your GUI. At this point make sure you save it, click on the picture of the disk to do so. You can now close the layour pannel. If you need to open it later you can choose "Open Existing GUI" from the GUIDE startup, or just type in "GUIDE" followed by the filename in the command window. At this point you may want to put some *.jpg's in the directory so you can test the code as you go.
Coding the GUI
Now that the layour for our GUI is complete we need to tell the objects how to behave via code.
- To begin you should type "edit" followed by the appropriate m-file. If you have been following along that would mean typing "edit test.m"
- A lot of the code has been already created by MATLAB as we were laying out our GUI. Let's first focus on the listbox. Our listbox was tagged "filelist" and has two functions associated with it. The first is filelist_CreateFcn. This function gets called by the filebox when the GUI is first started. The second is filelist_Callback. This function is called when the user interacts with the listbox. We will begin with the filelist_CreateFcn. When the listbox is created we want it to populate with all of the jpg's in the directory so that the user may chose them. The following code acomplishes that:
function filelist_CreateFcn(hObject, eventdata, handles)
This really is not as hard as it looks, let's break it down step by step. The first three lines of code after the comments are put there by MATLAB, our code starts after the break. filenames = dir('*.jpg') serves to read in all files in the directory into the structure filenames. since all we care about is the name field of this structure we extract them with the for loop and store them in a cell array fnames. Now we use a feature of GUIDE which is the set function. the hObject is the current object, which is the listbox. The 'String' referes to the property to set, and the fnames is the cell array you wish to set the property to. The next line handles.filename = fnames{get(hObject,'Value')} does two things. The first is extracting the Value from the current object. This refers to the index in the cell array that is currently selected in the listbox. We pass this parameter back to fnames to get the filename at that index. This is stored in a structure handles. Handles is a special structure that is constant throughout the whole GUI even though the various items are stored in different functions. Lastly guidata(hObject, handles) saves your changes to handles. This is neccesary every function in which you change the handles structure.
% hObject handle to filelist (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
filenames = dir('*.jpg');
fnames= {};
for i=1:length(filenames)
fnames = [fnames {filenames(i).name}];
end
set(hObject,'String',fnames);
handles.filename= fnames{get(hObject,'Value')};
guidata(hObject, handles);
- Now let's analyze the filelist_Callback function. The code that we want for this element is as follows:
function filelist_Callback(hObject, eventdata, handles)
This is a lot simpler than the preceding code. This executes whenever a new file is selected in the listbox. The first non-comment line get's the cell array from the filelist that represents the contents and stores it in the variable files. Next we get the currently selected index and extract the appropriate filename with it. This is reassigned to handles.filename. Since we modified handles we need to use the guidata function to update the structure.
% hObject handle to filelist (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns filelist contents as cell array
% contents{get(hObject,'Value')} returns selected item from filelist
files = get(hObject,'String');
handles.filename= files{get(hObject,'Value')};
guidata(hObject, handles);
- Next let's deal with the read button. We tagged this as "readButton" and the relevant function is readButton_Callback. The codes is as follows:
function readButton_Callback(hObject, eventdata, handles)
While this code looks pretty long, it should hopefully be the most familiar to you. The first line is an imread. We use the filename that we have stored in the handles structure. The second line displays the image, we do not need to specify where since we only made one axes on our GUI it will be automatic. You should recognize the next block as the creation of a grayscale version of the picture. The gray version is stored in the handles structure as handles.gray and the regular is handles.img. At this point we set the BW toggle button on using the set function and passing the handles.BWtoggle object in. We chose the 'Enable' property and set the value to 'On'. We then change the value to 0 so that every time you read in the image the toggle button is reset to the off position which we chose to mean color. Finally we save our changes to the handles object using the guidata function.
% hObject handle to readButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
img = imread(handles.filename);
imshow(img);
[r c l] = size(img);
for i = 1:r
for j = 1:c
gray(i,j,:) = 1/3*img(i,j,1)+1/3*img(i,j,2)+1/3*img(i,j,3);
end
end
handles.gray = gray;
handles.image = img;
set(handles.BWtoggle,'Enable','On');
set(handles.BWtoggle,'Value',0);
guidata(hObject, handles);
- The last part of this tutorial is the black and white toggle button. Remember we tagged this object as BWtoggle and the function is BWtoggle_Callback. The code is as follows:
function BWtoggle_Callback(hObject, eventdata, handles)
This code is very simple, get(hObject,'Value') returns a boolean. if it is true show the gray image, else show the color. There is no need to update handles as we haven't changed anything.
% hObject handle to BWtoggle (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of BWtoggle
if get(hObject,'Value')
imshow(handles.gray)
else
imshow(handles.image)
end