How to write multiple image from a for loop to a dir
Show older comments
Hi everyone, I'm trying write the output image of a "for loop" into a dir but instead writing all the output only four images is save in the directory. since it's a for loop, it's over-written the first four until the loop finishes. please help check the code, here it is below:
imds = imageDatastore ( 'D:\lfw' , ...
'IncludeSubfolders' , true, ...
'LabelSource' , 'foldernames' );
idx = randperm (numel (imds.Files), 5749);
j = 1;
count=0;
folder ='C:\Users\Asirajdin\Documents\T Chapters\Face Detection JKJJ\Class photos\Cropped';
% figure
for t = 1: 5749
img = readimage (imds, idx (t));
FaceDetect = vision.CascadeObjectDetector('FaceDetector-haar3.xml');
FaceDetect.MinSize=[32,32];
FaceDetect.MergeThreshold = 7;
BB = step (FaceDetect, img);
figure (2);
imshow (img);
for i = 1: size (BB, 1)
rectangle ( 'Position' , BB (i, :), 'LineWidth' , 3, 'LineStyle' , '-' , 'EdgeColor' , 'r' );
count = count+1;
end
hold off;
for i = 1: size (BB, 1)
J = imcrop (img, BB (i,:));
fileName = fullfile(folder,sprintf('Image %d.jpg',i));
imwrite(J,fileName) ;
figure (3);
subplot(11, 10,i);
imshow (J);
j = j + 1;
end
Answers (2)
Paul Hoffrichter
on 4 Dec 2020
I copied your method of writing the images to files and there were no problems.
Irgb = imread('Lena.jpg');
J = Irgb;
for i = 1:3
fileName = fullfile('.',sprintf('Image %d.jpg',i));
imwrite(J,fileName) ;
end
I verified as follows:
i1 = imread('Image 1.jpg');
i2 = imread('Image 2.jpg');
i3 = imread('Image 3.jpg');
imshow(i1)
imshow(i2)
imshow(i3)
Rik
on 4 Dec 2020
0 votes
Assuming the missing end keyword goes at the end:
Your filename depends on only the inner loop, not the outer loop.
2 Comments
Paul Hoffrichter
on 4 Dec 2020
Edited: Paul Hoffrichter
on 4 Dec 2020
Was not concerned about that that since, as you know, MATLAB is kind enough to point that out immediately. Just a copy and paste mistake.
Rik
on 5 Dec 2020
That is what assumed as well, hence my answer.
Categories
Find more on Convert Image Type in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!