I'm guessing that you will have some sort of GUI or even just a figure that has the displayed image. And so long as your GUI or figure has focus, then you want it to respond to the key presses and act accordingly.
You can do this by simply adding a Key Press callback to a figure. When the user presses a key, the callback will fire and you can handle the event based on the key.
A very simple example that will change the image upon pressing the left and right arrows is
function catchKeyPress
h = figure;
set(h,'KeyPressFcn',@KeyPressCb) ;
I = imread('someImageA.jpg');
imshow(I);
function KeyPressCb(~,evnt)
fprintf('key pressed: %s\n',evnt.Key);
if strcmpi(evnt.Key,'leftarrow')
I = imread('someImageB.jpg');
imshow(I);
elseif strcmpi(evnt.Key,'rightarrow')
I = imread('someImageA.jpg');
imshow(I);
end
end
end
The above will create a figure and assign a callback for the KeyPressFcn event. The body of the callback fires for every key pressed and, in this case, handles the left and right arrow keys.
Try it and see what happens!
Best Answer