How to set CurrentTime for VideoReader in parfor loop

7 views (last 30 days)
In order to hasten the processing time, I am attempting to read the frames of a VideoReader object within a parfor loop with the following code:
video = VideoReader("myvideo.mkv");
parfor k = 1:floor(video.Duration)
frame_number = k;
img = readthisframe(video, frame_number);
end
Where the function readthisframe is:
function outputFrame=readthisframe(video,frame_number)
info=get(video);
video.CurrentTime=frame_number;
outputFrame=readFrame(video);
(this function was derived from another thread written by Patrick Feaster, https://www.mathworks.com/matlabcentral/answers/298991-reading-in-only-specific-video-frames-with-readframe)
When I run this code, though, I get the following error message:
Error using readthisframe (line 4)
No more frames available to read from file.
I believe that this is happening because the CurrentTime does not reset everytime I read a frame from the video file and instead progresses until it hits the end of the video. However, I cannot find a way of reseting CurrentTime in every iteration of the parfor loop. Is there an easy way to do this, or does this error stem from a different issue with the code?

Accepted Answer

Walter Roberson
Walter Roberson on 22 May 2019
"Timestamp of the video frame to read, specified as a numeric scalar. The timestamp is specified in seconds from the start of the video file. The value of CurrentTime can be between zero and the duration of the video."
You are trying to use frame numbers as the current time, which expects seconds. You are going to have problems unless the frame rate is 1 fps
The read() method accepts frame numbers.
On most videos it is difficult to exactly calculate between times and frame numbers. The Framerate property is often an approximation or nominal rate such saying that ntsc is 30 fps when really it is 29.97-something. You also see ntsc frame rates in files given as 29.97 which is not exactly right either.
On variable frame rate files you can only talk about average frame rates but it could change depending on the content of the frames (more complex detail changes require more bandwidth)
Frames are tagged with timestamps not with frame numbers so asking for a particular time is the safest route to get the frame for exactly that time. However for your purposes you are using frame numbers not times.
Warning: asking for particular frame numbers can require that the entire file be read from the beginning.
Warning: having multiple processes read from the same file usually slows down i/o because disk bandwidth is limited and you are forcing seeking back and forth rather than sequential reading. The only case in which it can speed up i/o is the case where processing each frame once it is read is slower than reading the frame from disk.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!