MATLAB: Display random image on axes

imagerandom image

I have set of image in one folder. How can I display random image from a folder when i click on a pushbutton?

Best Answer

%first you need to get the names of the images
projectdir = '/homes/users/hani/MATLAB/plan9/images'; %set as appropriate
img_exts = {'bmp', 'gif', 'jpg', 'png', 'tif'}; %list all the extensions you want to include
dinfo = [];
for K = 1 : length(img_exts)
dinfo = vertcat(dinfo, ...
dir( fullfile(projectdir, ['*.', img_exts{K}]) ) );
end
%now pick one randomly
randidx = randi( length(dinfo) );
randomfile = fullfile( projectdir, dinfo(randidx).name );
%read it
imagedata = imread(randomfile);
image(handles.TheDestinationAxes, imagedata); %display it
You will find it more efficient to create dinfo only once and store the data somewhere to be used when the button is pushed.