How to save image in directory in MATLAB

조회 수: 7 (최근 30일)
Stephen john
Stephen john 2022년 3월 18일
댓글: Bjorn Gustavsson 2022년 3월 18일
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

답변 (1개)

Bjorn Gustavsson
Bjorn Gustavsson 2022년 3월 18일
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
Stephen john
Stephen john 2022년 3월 18일
@Bjorn Gustavsson not working
Bjorn Gustavsson
Bjorn Gustavsson 2022년 3월 18일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Images에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by