Use keyboard input to assign value to a variable

I have a series of images that I'd like to display one at a time and be able to change something like the brightness or contrast by using keyboard keys (say up or down arrow) and when I'm satisfied with that image, use left or right arrows to move between images. To that end, I'd like to have some sort of function that, upon pressing a keyboard key, outputs a value that depends on the key pressed. I could do something like this with ginput, where the button output is 1, 2, or 3 depending on if I left, right, or middle click, but that would limit me to only 3 different options, while I want at least 4, if not 6 or 8 different options. Any ideas?

댓글 수: 1

Had a question similar to this, but wanted to update a variable depending on the key that was pressed in 'real time'. Because it doesn't seem to exist anywhere else here is the code that will allow you to assign a variable, s, with either space, leftarrow, or rightarrow, when you click one of those three. It's a small variation on Geoff's code below.
function catchKeyPress
h = figure;
set(h,'KeyPressFcn',@KeyPressCb);
function y = KeyPressCb(~,evnt)
fprintf('key pressed: %s\n',evnt.Key);
global s;
if strcmp(evnt.Key,'rightarrow')==1
s = evnt.Key;
elseif strcmp(evnt.Key, 'leftarrow')==1
s = evnt.Key;
elseif strcmp(evnt.Key,'space')==1
s = evnt.Key;
end
end
end
In order for this to work you need to call the function catchKeyPress from a separate script. Thanks Geoff for the script which let me figure this out. end

댓글을 달려면 로그인하십시오.

 채택된 답변

Geoff Hayes
Geoff Hayes 2014년 6월 22일

3 개 추천

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!

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Desktop에 대해 자세히 알아보기

질문:

2014년 6월 21일

편집:

2016년 12월 7일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by