Russell Chow
Russell Chow

Reputation: 27

Batch process and name/save images in a separate folder

I am running a script to create masks of 41 Controls, both Positive and Negative, for a total of 82 images. I don't know how to save the masks with names similar to the original .png files, such as "Masked Control_1 Positive", "Masked Control_1 Negative", etc to Control_41. I also don't know how to save these to a separate folder within my current folder. Thank you!

I have also included a screenshot of the current directory.

enter image description here

% GlassBrains_Controls2Mask.m
clear;

Files = dir('Control_*');
Controls_Results_Structure = struct('BW',[],'maskedRGBImage',[]);

for i = 1:length(Files)
    RGB = imread(Files(i).name);
    [Output_BW, Output_maskedRGBImage] = GlassBrainMask(RGB);
    Controls_Results_Structure(i).BW = Output_BW;
    Controls_Results_Structure(i).maskedRGBImage = Output_maskedRGBImage; 
end

save("Controls_Results_Structure")

% Save the results
mkdir "Masked Glass Brains (Controls)"
for i = 1:length(Files)
    Image_Number = i;
    save(Controls_Results_Structure(Image_Number).BW);
   
end

Upvotes: 0

Views: 151

Answers (1)

Vicky
Vicky

Reputation: 949

Please notice that save() stores workspace variables in MAT files, which are generally meant to be opened with MATLAB only, not with image viewers and such. PNG files like those you are reading with imread() can be created with imwrite():

% Save the results
outdir='./Masked Glass Brains (Controls)';
[mkdir_status,~,~]=mkdir(outdir);
assert(mkdir_status,'Error creating output folder.');
clear mkdir_status;

for i=1:length(Files)
  imwrite( Controls_Results_Structure(i).BW, ...
    sprintf('%s/Masked %s',outdir,Files(i).name) ... %alternative: [outdir  '/Masked '  Files(i).name]
    );
end

To customize the image file that imwrite() creates from the output of GlassBrainMask(), see: https://www.mathworks.com/help/matlab/ref/imwrite.html

Upvotes: 1

Related Questions