MATLAB: Using GUI, use one push button as an image browser and another to process the image that was chosen

digital image processingguiguideImage Acquisition Toolboximage processingImage Processing Toolboxmatlab gui

Hi I'm creating a GUI for part of an image processing project at university. To this point I've created a push button which allows me to browse through my working directory and select either a 'jpg' or 'bmp' image: below is the code:
% --- Executes on button press in pushbutton1(Image Browser).
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

[filename pathname] = uigetfile({'*.jpg';'*.bmp'},'File Selector');
image = strcat(pathname, filename);
axes(handles.axes1);
imshow(image)
set(handles.edit1,'string',filename);
set(handles.edit2,'string',image);
I'm looking to create another push button which will plot a histogram of the image I read in, I'm not sure how to define the image under the new function as the image that was chosen previously, could any one help, below is the code I have at the minute for the histogram push button but it is giving out errors;
% --- Executes on button press in pushbutton2 (Histogram plot).
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
axes(handles.axes1);
histogram(double(image(:)),'Normalization','pdf');
could any one help me out?

Best Answer

Sean - image is the name of a built-in MATLAB function so it is not a good idea to name your variable image and so you should rename it to something else.
As for having your second callback be "aware" of the image that was chosen in the first callback, note the comment for the handles structure input
% handles structure with handles and user data (see GUIDATA)
You can update this structure with the image (user data) in the first callback so that any other callbacks that receive handles as an input will have access to it. Try something like
function pushbutton1_Callback(hObject, eventdata, handles)
[filename pathname] = uigetfile({'*.jpg';'*.bmp'},'File Selector');
handles.myImage = strcat(pathname, filename);
axes(handles.axes1);
imshow(handles.myImage)
set(handles.edit1,'string',filename);
set(handles.edit2,'string',image);
% save the updated handles object
guidata(hObject,handles);
In your second callback, just reference the loaded image as handles.myImage as
function pushbutton2_Callback(hObject, eventdata, handles)
if isfield(handles,'myImage')
% do stuff
end
Try the above and see what happens!