Clear Filters
Clear Filters

How to speed up frame-by-frame image processing for writing a video?

36 views (last 30 days)
I have a large video (avi) that I want to read, process each frame, crop, and save a processed video. Here is my example script, which takes extraordinally long time to run (~35 seconds/100 frames). Is there more efficient way to read, process, and write frames to a video?
% Read video
fname = 'vid.avi';
n_frames = reader.NumFrames;
crop_position = [1000, 300, 149, 99];
% Write video
writer = VideoWriter('cropped_vid', 'MPEG-4');
writer.Quality = 95;
writer.FrameRate = reader.FrameRate;
% process frames
for i=1:n_frames
img = read(reader,i);
img = rgb2lab(img);
img = imcomplement(imreducehaze(imcomplement(img(:,:,1) ./ 100),'ContrastEnhancement','boost'));
img = medfilt2(imcrop(img,crop_mask),[5,5]);
img = imcomplement(imreducehaze(imcomplement(img)));
Yair Altman
Yair Altman on 9 Feb 2022
The first thing that I suggest to do is to run your script in the Matlab Profiler, for example by clicking the <Run and Time> button in the Editor. This will tell you where most of the run-time is spent:
  1. perhaps it's reading the input video with read(reader,1)?
  2. perhaps it's in the rgb2lab conversion?
  3. perhaps it's the processing of each frame?
  4. perhaps it's writing to the output video using writeVideo?
Based on what you discover, it will be easier to focus your speed-up efforts. For example, perhaps you can vectorize some operations rather than processing the frames one-by-one; or perhaps you can move the the read/write parts outside the loop for faster I/O; or perhaps you can improve the processing by using a custom conversion. Before you know where the main bottleneck is, the efforts will be wasted.
Walter Roberson
Walter Roberson on 9 Feb 2022
User already said, "the most of the time is in the code is spent in rgb2lab conversion"

Sign in to comment.

Answers (1)

yanqi liu
yanqi liu on 8 Feb 2022
yes,sir,may be split image process and video write,such as process image to files,and then read files and write to video,so it will avoid video write flush step

Community Treasure Hunt

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

Start Hunting!