Unable to acquire *precisely* timed videos in Matlab (using ImgAcq toolbox) - matlab

When I try to record using the code below, the resulting videos have the correct number of frames and file lengths, but the recorded time is always slightly longer (as measured by filming a digital clock), a 60min recordings capture ~61min, and 5min recordings have extra 3-5sec (so time is skipped during recordings). Occasionally, the camera clearly show time skipping when it records for some time, then pauses for up to hour or so, and then resumes.
I am using a Basler GigE acA1300-60gm (http://www.baslerweb.com/en/products/area-scan-cameras/ace/aca1300-60gm) camera set to continuous triggering for several hours, and I need the acquired videos to have millisecond resolution. I am not sure why the recording times are so varied, am I using a wrong script for the job or does it have something to do with the hardware settings?
(Matlab R2014a on Windows 7)
vid = videoinput(adapter, deviceIDVar{1,1}, formatVar);
vid.FramesPerTrigger = NoOfFramesPerFile;
src = getselectedsource(vid);
src.FrameStartTriggerMode = 'On';
src.FrameStartTriggerSource = 'Line1';
src.FrameStartTriggerActivation = 'RisingEdge';
src.FrameStartTriggerMode = 'Off';
src.PacketSize = 8000;
triggerconfig(vid, 'hardware', 'DeviceSpecific', 'DeviceSpecific');
vid.TriggerRepeat = 0;
vid.LoggingMode = 'disk';
for i=1:FileLimit
%file path and format settings
diskLogger = VideoWriter(filenameWithExt, 'MPEG-4');
diskLogger.FrameRate = 25;
vid.DiskLogger = diskLogger;
start(vid)
wait(vid, Inf);
end
stop(vid)
delete(vid)
clear
Are here any better ways to acquire precisely timed videos (at 25FPS)? Thanks in advance!

Related

STM32 HAL Nucleo F446RE Quadrature Encoder

I have a problem with the quadrature encoder mode on timer TIM3 of my
STM32F446RE /
NUCLEO-F446RE:
TIM3 counts on every rising edge on the first signal.
The CNT register counts up and I read the value with 1 Hz and then
I set the register to 0.
When I look on the
oscilloscope
the frequency is half as high as the value from the
CNT register output (1hz).
Why?
TIM3 counts on both edges on the first signal.
The
CNT register output (1 Hz)
is completely wrong.
My configuration is:
GPIO_InitTypeDef sInitEncoderPin1;
sInitEncoderPin1.Pin = pin1Encoder.pin; // A GPIO_PIN_6
sInitEncoderPin1.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin1.Pull = GPIO_PULLUP;
sInitEncoderPin1.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin1.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
GPIO_InitTypeDef sInitEncoderPin2;
sInitEncoderPin2.Pin = pin2Encoder.pin; // A GPIO_PIN_7
sInitEncoderPin2.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin2.Pull = GPIO_PULLUP;
sInitEncoderPin2.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin2.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
HAL_GPIO_Init(GPIOA, &sInitEncoderPin1);
HAL_GPIO_Init(GPIOA, &sInitEncoderPin2);
encoderTimer.Init.Period = 0xffff;
encoderTimer.Init.Prescaler = 0;
encoderTimer.Init.CounterMode = TIM_COUNTERMODE_UP;
encoderTimer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
encoderTimer.Init.RepetitionCounter = 0;
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 1);
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
encoder.IC1Filter = 0x0f;
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING; // TIM_INPUTCHANNELPOLARITY_BOTHEDGE
encoder.IC1Prescaler = TIM_ICPSC_DIV1;
encoder.IC1Selection = TIM_ICSELECTION_DIRECTTI;
encoder.IC2Filter = 0x0f;
encoder.IC2Polarity = TIM_INPUTCHANNELPOLARITY_RISING;
encoder.IC2Prescaler = TIM_ICPSC_DIV1;
encoder.IC2Selection = TIM_ICSELECTION_DIRECTTI;
HAL_TIM_Encoder_Init(&encoderTimer, &encoder);
HAL_TIM_Encoder_Start_IT(&encoderTimer, TIM_CHANNEL_ALL);
The
oscilloscope screenshot
shows a frequency of about 416 Hz.
The values shown in the
first shell output
are (very roughly!) twice as high (as the question points out already).
This appears (nearly...) correct to me since the shown configuration
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
selects the "X2 resolution encoder mode", which counts 2 CNT increments per signal period.
In an application note on
timer overview,
(Sec. 4.3.4 / Fig. 7) there is an illustrative diagram how the encoder mode works in detail.
The
second screenshot
results from an incorrect TIM3 configuration:
The encoder mode (TIM_ENCODERMODE_TI1) assumes that both channels trigger only upon directed flanks in an alternating way (see the AN link above).
If one of the two channels triggers twice as many events due to
configuration
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE,
the counter will only count up one position and then "recognize" a "reversal" event (= change of direction).
Keeping in mind that
65535u = 0xFFFF = -1
the second screenshot only shows values -1, 0, +1 - which fits perfectly with this explanation.
The question remains why the first screenshot shows (reproducible) measurements between 800 and 822.
I assume that
the physical source of the encoder signal runs at a constant pace
the 1 Hz timer that triggered shell output is independent from TIM3, and
it has been started before the encoder timer
(i.e., above the shown code sample).
This may explain why the first two values look like nonsense (0: TIM3 has not been started yet. 545: TIM3 has been started during the shell output timer period).
Discarding the first two measurement samples, the average and standard deviation, resp., of the measured signal frequency are
808,9091 +/- 0,5950 [X2 increments per second]
404,4545 +/- 0,2975 [Hz]
which corresponds to a period of
2,4331 +/- 0,003 [ms].
Hence, the measured frequency is too low by about 11 Hz, i.e., measured period too high by nearly 30 µs, and this error is clearly beyond the statistical noise.
The question gives a hint where this error might come from:
The CNT register counts up and I read the value with 1 Hz and then I set the register to 0.
Whenever the 1 Hz "polling timer" expires, it triggers an interrupt
(or a logical event in polling software).
Processing of this interrupt/event may be delayed a little,
depending on other software (IRQ: deactivation times elsewhere in the software,
Polling: loop duration until event is polled).
Software reads CNT value.
Software resets CNT value to zero,
discarding further increments since the CNT value has been read.
TIM3 continues counting (from zero).
This hints that software needs 30 µs between (3.) and (4.), which would be quite a lot of time on an STM32F4.
Edit: I just re-checked the oscilloscope screenshot. The error is visible, but I believe it is smaller than I originally assumed (from counting flanks in the picture).

Given FrameRate does not match with real FrameRate

I am testing my laptop integrated cam, and after writing this simple code, FrameRates doesn't match. It shows that it's 30fps, but after calc I can see it's the half, 15fps. This is the code:
vid = videoinput('winvideo',1);
frameRates = set(getselectedsource(vid), 'FrameRate')
vid.FramesPerTrigger = 30;
start(vid); [frames, timeStamp] = getdata(vid);
frameRateCalc = 1/mean(diff(timeStamp))
And this is the output
>> framerate
frameRates =
'30.0000'
frameRateCalc =
15.2007
I have tested with another external cam and seems to work fine, 30 match with 30. Anybody knows why they doesn't match with the integrated cam?

Create video with identical frames in matlab

I am creating a video for a presentation with matlab. The video shows a optimization algorithm moving towards the minimum of a costfunction. I want the last seconds of the video to be a freeze-frame, which means that I use the writevideo function to write a couple of identical frames. However when I play the video with VLC player or with powerpoint the correct length of the video is shown, but the identical frames of the video are "skipped". Is there any way I can stop this?
My Code looks like this:
graph = figure('units','pixels','position',[0 0 1920 1080]);
scatter3... %(first frame)
v = VideoWriter('Presentation.avi');
v.Quality = 95;
v.FrameRate = 1;
open(v);
frame = getframe(graph);
writeVideo(v,frame);
for i = 1:10
plot3... %(changing frames)
frame = getframe(graph);
writeVideo(v,frame);
end
for j = 1:5
%(identical frames)
frame = getframe(graph);
writeVideo(v,frame);
end
close(v);
Thank you for answering!

present video and record from webcam - matlab

I wrote a script that present movie and record from the webcam. The problem is that it rolls the movie in slow motion. I don't think the problem is from taking the snapshot ( I checked it). This is the code:
clear cam
v = VideoReader('movie.MP4');
cam = webcam;
vidWriter = VideoWriter('webcam.avi');
open(vidWriter);
%pre loading the frames
for i=1:50
vtemp = readFrame(v);
vid{i}=vtemp;
end
for index = 1:50
% Acquire frame for processing
img = snapshot(cam);
% Write frame to video
writeVideo(vidWriter, img);
%show the vid frame
imshow(vid{index});
end
close(vidWriter);
clear cam
Any assistance will be much appreciated.

Flicker frequencies in PTB

I'm trying to present a 4Hz flickering stimuli in PsychToolbox for 5 seconds followed by a 500Hz tone. Does anyone have an idea of how to do this? I've been using the vbl or screen refresh rate to calculate the flicker frequency but I'm not sure if I'm on the right track at all. I also have no idea how to present an auditory stimuli in PTB (I tried the sound function already). Any help is greatly appreciated!
I'm not sure about sound presentation in PTB (I've never done it), but you seem to be on the right track for the flicker frequency.
The way I do it is to determine the screen refresh rate, divide the total length of time you want the stimulus presented by this refresh rate (this will give you the number of frames that will be drawn during this time), and then have a frame counter that increases by 1 after every flip. You can then use this frame counter to switch commands on or off.
A minimal example (randomly changes the background colour at 4Hz for 5 seconds):
[w, wRect]=Screen('OpenWindow', 0);
MaxTime = 5; %Set maximum time for all stimuli to be presented in seconds
Hz = 4; %Set Hz for stimulus flicker
Screen('Flip',w);
Frametime=Screen('GetFlipInterval',w); %Find refresh rate in seconds
FramesPerFull = round(5/Frametime); % Number of frames for all stimuli
FramesPerStim = round((1/Hz)/Frametime); %Number of frames for each stimulus
StartT = GetSecs; %Measure start time of session
Framecounter = 0; %Frame counter begins at 0
while 1
if Framecounter==FramesPerFull
break; %End session
end
if ~mod(Framecounter,FramesPerStim)
randomcolour = rand(1, 3)*255; %Change background stimulus colour
end
Screen('FillRect', w, randomcolour, wRect);
Screen('Flip',w);
Framecounter = Framecounter + 1; %Increase frame counter
end
EndT = GetSecs; %Measure end time of session
Screen('CloseAll');
EndT - StartT %Shows full length of time all stimuli were presented
The timing precision will depend on your particular refresh rate.
Hope this helps!