Batch process and name/save images in a separate folder

6 views (last 30 days)
Hello!
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.
% 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

Accepted Answer

Alamanda Ponappa Poovaya
Alamanda Ponappa Poovaya on 22 Mar 2021
I understand you want to save your final images in a separate folder in the current folder with names similar to the original PNG files. You can do so by combining both the for loops, using split and concatenation to get your output file names as intended and using imwrite to save them to your new folder
Based on your screenshot, I have assumed your code is in the same file as all your png files and that you want to create a new folder within the current folder
I am attaching your code below with these changes
clear;
Files = dir('*.png');
mkdir 'Masked Glass Brains (Controls)'
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;
% Create file name and save to directory
name = split(Files(i).name);
filename = ['Masked ', name{1}, ' ', name{2}];
imwrite(Output_BW,['Masked Glass Brains (Controls)\',filename]);
end
save("Controls_Results_Structure")

More Answers (0)

Community Treasure Hunt

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

Start Hunting!