MATLAB Answers

Sequential image writing in a loop

3 views (last 30 days)
JohnDylon on 11 Jun 2016
Commented: Image Analyst on 14 Jun 2016
I'm trying to develop a code simply reads frames from a video, processes the frames and then writes them back to an output video. My code in general works but the output video have some issues that I detected and couldn't figure out.
The problem occurs at the step of creating a video from processed frames. If my frames are named like 001.png, 002.png, etc. the following code calls all them in correct sequence, i.e. first 001.png, second 002.png, etc. The code is:
close all;
clear all;
workingDir1 = 'C:\Users\John\MATLAB\bin\Delete\';
workingDir2 = 'C:\Users\John\MATLAB\bin\Test_Grow2_Frames\';
imageNames1 = dir(fullfile(workingDir1,'*.png'));
imageNames1 = {}';
imageNames2 = dir(fullfile(workingDir2,'*.png'));
imageNames2 = {}';
for k = 1:length(imageNames1)
img1 = imread(toread1);
img2 = imread(toread2);
imshow([img1 img2]);
In the code, 'C:\Users\John\MATLAB\bin\Delete\' folder contains images named as 1.png, 2.png, 3.png up to 329.png and 'C:\Users\John\MATLAB\bin\Test_Grow2_Frames\' folder contains images named as 001.png, 002.png, etc. up to 329.png.
The interesting part is here: When the for loop iterates
  • k=1, toread1 has the value 1.png and toread2 has the value 001.png which is OK,
  • k=2, toread1 has the value 10.png and toread2 has the value 002.png which is not OK for toread1 since it supposed to be 2.png,
  • k=3, toread1 --> 100.png, toread2 --> 003.png,
  • k=4, toread1 --> 101.png, toread2 --> 004.png.
So there is a something going on here, can anybody help on that?
BTW, I generate 1.png, 2.png type names with the code:
imwrite(RGB,['C:\Users\John\MATLAB\bin\Delete\', num2str(curr_frm_num), '.png']);
If someone has an idea to generate 001.png type names, it is also appreciated.

Accepted Answer

Image Analyst
Image Analyst on 11 Jun 2016
I do this in my demo, which I've posted many times. I attach it here.
Image Analyst
Image Analyst on 14 Jun 2016
If it sorts alphanumerically then that's right. This is a well known problem. See the FAQ:

Sign in to comment.

More Answers (1)

JohnDylon on 11 Jun 2016
For the naming as 001.png part I've already had the solution as:
imwrite(RGB,['C:\Users\John\MATLAB\bin\', sprintf('%3.3d.png', 1)]);
which is working.

Community Treasure Hunt

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

Start Hunting!

Translated by