Record 2 USB video at the same time

4 次查看(过去 30 天)
Hi,
I try to record the video from USB camera in a duration (For example: 100seconds). I use the timer function to stop the recording video.
However, the output video is longer than my expetected (around 116 seconds).
Is there any problem with my method?
Thank you
people = "User1";
cam1 = webcam(1);
No webcams have been detected. Please ensure the webcam is connected to the system.
cam2 = webcam(2);
dayTime = strrep(datestr(datetime),':','_');
dayTime = regexprep(dayTime,{' '},{'_'});
cam1.Resolution="640x480";
cam2.Resolution="640x480";
video_name1 = people + "Cam_1_"+dayTime+".MP4";
video_name2 = people + "Cam_2_"+dayTime+".MP4";
video_1 = VideoWriter(video_name1,'MPEG-4');
video_2 = VideoWriter(video_name2,'MPEG-4');
video_1.FrameRate = 30;
video_2.FrameRate = 30;
open(video_1);
open(video_2);
file_name = 'CreatedTime_Video.txt';
writematrix(dayTime,file_name,'Delimiter',',')
t = timer('TimerFcn', 'stat=false; disp("Start record video")',...
'StartDelay',100);
start(t);
stat = true;
tic;
while(stat == true)
I1 = snapshot(cam1);
writeVideo(video_1,I1);
I2 = snapshot(cam2);
writeVideo(video_2,I2);
end
close(video_1);
close(video_2);

回答(1 个)

colordepth
colordepth 2024-12-27
When recording video from USB cameras, using a timer can lead to inaccuracies in the video duration. Timers in MATLAB can be unreliable if the system is busy, you may learn more about the limitations of the “timer” function in the official documentation: https://www.mathworks.com/help/releases/R2022b/matlab/ref/timer.html.
As a workaround, you can rely on the frame rates of your cameras to control the recording time. For the basic scenario where both cameras have the same frame rate, such as 30 fps in your case, you can use a simple for loop to capture frames for the desired duration:
for i = 1:(100 * video_1.FrameRate)
% Call “snapshot” and “writeVideo” same as before
end
For cases where the frame rates differ, such as 24 fps and 30 fps, you can use a time-based loop to synchronize the frame captures accurately:
% Time step size based on the maximum frame rate
timeStep = 1 / max(frameRate1, frameRate2);
% Error threshold for floating-point comparison
errThreshold = 1e-4;
% Duration for capturing video in seconds
captureDuration = 100;
for t = 0:timeStep:captureDuration - timeStep
if abs(mod(t, 1 / frameRate1)) < errThreshold
I1 = snapshot(cam1);
writeVideo(video_1, I1);
end
if abs(mod(t, 1 / frameRate2)) < errThreshold
I2 = snapshot(cam2);
writeVideo(video_2, I2);
end
end

类别

Help CenterFile Exchange 中查找有关 MATLAB Support Package for IP Cameras 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by