Stop execution of function using a specific key press

Hello,
I am trying to write a program where the user has to click several times on a video that is being played. After the user has clicked on the video as many times as he/she wanted, he/she has to end his/her 'clicking session' by pressing a specific key (e.g. when pressing 'g'). I'm thinking of using 'waitforbuttonpress', but is there any way to specify that a specific key has to be pressed before the script continues?
So far, I've been using the 'imrect' and 'wait' command to achieve this. So after the user has clicked as many times as he/she wanted, he/she has to draw a rectangle to terminate his/her clicking session. But now I am looking for a more convenient way to stop the execution by pressing a specific key.
Here is my code:
vid = VideoReader('test1.mp4'); %make VideoReader object
curr_axes = axes;
hfig = figure(1);
set(hfig,'WindowButtonDownFcn',@countclicks) %use callback (user clicking on video)
framecount = 0;
while vid.hasFrame() %play video
temp = vid.readFrame();
framecount = framecount + 1;
curr_time(framecount) = vid.CurrentTime;
image(temp,'Parent',curr_axes);
curr_axes.Visible = 'off';
pause(0.05/vid.FrameRate);
if framecount == 78 || framecount == 78*2 || framecount == 78*3 %after every 3 seconds, the user has to draw a rectangle before proceeding
p1 = imrect; %draw a rectangle to proceed to the next 3 seconds of the video
wait(p1)
end
end
function countclicks(gcbo,eventdata,handles)
disp(get(gcf,'SelectionType'))
disp(get(gcf,'CurrentPoint'))
end

 Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 18 Jun. 2020

0 Stimmen

See WindowKeyPressFcn callback(): https://www.mathworks.com/help/releases/R2020a/matlab/ref/matlab.ui.figure-properties.html#buiwuyk-1-WindowKeyPressFcn. This callback also passes the key-pressed by the user, so you can make different decisions based the keypress.

4 Kommentare

Sam
Sam am 18 Jun. 2020
Thank you very much! How would this be implemented?
It is just like a regular callback function. For example, run the following code
fig = figure('WindowKeyPressFcn', @keyPressFcn)
function keyPressFcn(obj, eve)
disp(eve);
end
and press the keys while the figure window is focused.
Sam
Sam am 18 Jun. 2020
Thank you. But now the video doesn't pause every 3 seconds anymore
This just shows an example of how the callback works. You need to modify it according to your program logic.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Gefragt:

Sam
am 18 Jun. 2020

Kommentiert:

am 18 Jun. 2020

Community Treasure Hunt

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

Start Hunting!

Translated by