How to save image in directory in MATLAB

9 views (last 30 days)
Hello everyone , i hope you are doing well.
i have the following code in which i create six directory and save images to corresponding directory,
I want to create a directory in which all these directory are subdirectory and save images to corresponding directory
Can anybody help me
for example a directory created name 'Dataset' and all directory ('C1','C2','C3','C4','C5','C6') are in this one directory and save images to corresponding directory
[labelNums,~,labelIdx] = unique(labels,'rows');
labelStrs = {'C1','C2','C3','C4','C5','C6'};
%% make the folders
for ii = 1:numel(labelStrs)
labelStr = labelStrs{ii};
if ~isfolder(labelStr)
mkdir(labelStr);
end
end
[numImages, lenImage] = size(Dataset);
imSz = 1000; % assuming images are 1000x1000
imbg = false(imSz);
imfg = ~imbg(1,1);
imSizeOut=[1000 1000];
for imNum = 1:numImages
imData = round(Dataset1000(imNum,:));
[~,Y] = meshgrid(1:imSz);
% black and white image
BW = imbg;
BW(Y==imData)=imfg;
% resize (from 1000x1000)
BW=imbinarize(imresize(double(BW),imSizeOut));
% convert to uint8 (0 255)
im = im2uint8(BW);
im = flipud(im);
folderName = labelStrs{labelIdx(imNum)};
im_FullFilename = fullfile(folderName,sprintf('im_%06g.png',imNum));
imwrite(im,im_FullFilename);
end

Answers (1)

Bjorn Gustavsson
Bjorn Gustavsson on 18 Mar 2022
For this type of folder-related work I typically define a basedir that make it possible to run the script from any directory:
basedir = fullfile('mnt','data','DataSet')
% On Linux/Unix-type filesystems this will make basedir
% '/mnt/data/DataSet'
Then you can generate the full path to the directory by changing either to
folderName = fullfile(basedir,labelStrs{labelIdx(imNum)});
im_FullFilename = fullfile(folderName,sprintf('im_%06g.png',imNum));
or
im_FullFilename = fullfile(basedir,folderName,sprintf('im_%06g.png',imNum));
HTH
  3 Comments
Bjorn Gustavsson
Bjorn Gustavsson on 18 Mar 2022
OK, then you will have to make a similar enough modification of your first loop, from:
for ii = 1:numel(labelStrs)
labelStr = labelStrs{ii};
if ~isfolder(labelStr)
mkdir(labelStr);
end
end
to something like:
if ~isfolder(basedir)
mkdir(basedir)
end
for ii = 1:numel(labelStrs)
dirname = fullfile(basedir,labelStrs{ii});
if ~isfolder(dirname)
mkdir(dirname);
end
end
To get more relevant help it will help if you include error-messages and other relevant informatinon in addition to the "it doesn't work" that doesn't tell us anything relevant for bug-hunting.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by