How to make imshow function faster in the for loop?

21 views (last 30 days)
I want to generate a video in the figure window with its original sound, and I extracted total of 6600 frames from the video and saved them in the folder 'VideoFrames' with name 'p1' to 'p6600'.
Below in the for loop I call imshow to display each frame as they "become" the video, but they still are not at the same pace as the sound.
The imshow function takes most of time to run in the profiler, so it's necessary to improve the step of displaying images.
Below is the part of code:
[Y, Fs] = audioread('FruitVideo.mp4');
sound = audioplayer(Y, Fs); % get the audioplayer object
for j = 1:6600 % total frames are 6600
% get each frame image by using the path name & file in index
imageData = strcat('D:\ProgramFiles\MATLAB\InterDir\NetVideos\VideoFrames\p', num2str(j), '.bmp');
% read each frame image
framImage = imread(imageData);
% display each frame in the loop
imshow(framImage);
% After #40 of frame, playing the sound,
% but the images still generates slower than the sound
if j == 40
sound.play;
end
end

Answers (1)

Walter Roberson
Walter Roberson on 1 Dec 2021
To make imshow() faster...
Don't call imshow()
Seriously: imshow() has a lot of overhead.
Instead, call image() once and record the handle. Then each iteration through the loop, set the CData property of the image() object to the new data to be displayed.
Reminder: store your directory name in a variable, and use fullfile() to create the path.
imageData = fullfile(ImageDirectory, "p" + i + ".bmp");
  2 Comments
William Wang
William Wang on 4 Dec 2021
Thanks for this help!
I tried for image() getting object, and I notice that bmp format might have different return type of array making image() to display differently.
The format of image file matters, so I might need a little conversion of the file data, or can I use ".jpg" instead?
Walter Roberson
Walter Roberson on 4 Dec 2021
[Y, Fs] = audioread('FruitVideo.mp4');
ImageDirectory = 'D:\ProgramFiles\MATLAB\InterDir\NetVideos\VideoFrames';
sound = audioplayer(Y, Fs); % get the audioplayer object
for j = 1:6600 % total frames are 6600
% get each frame image by using the path name & file in index
imageData = fullfile(ImageDirectory, "p" + j + ".bmp");
% read each frame image
framImage = imread(imageData);
% display each frame in the loop
if j == 1
h = image(framImage);
else
h.CData = framImage;
end
drawnow()
% After #40 of frame, playing the sound,
% but the images still generates slower than the sound
if j == 40
sound.play;
end
end

Sign in to comment.

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!