MATLAB Answers

Thresholding for different values and save all figures automatically

10 views (last 30 days)
Hello guys i have a code that works and gives me the desired result (takes a grayscale or not image and thresholds and calxulates the fractal dim) but i would like help if anyone knows how can i firstly make the code run for multiple values of threshold , for example 0.3 , 0.4 , up to 0.7 and after that how to do the boxcount method that follows for each threshold and save all the figures that come up in the same folder?
What i mean is that i want the second part of the code from (Black=im2bw(Pic, 0.3); up to the end repeated for the numbers 0.3 0.4 0.5 0.6 0.7 and save all the figures and graphs in the same folder)
Thanks in advance!!
This is my code:
clear all
%Image = rgb2gray(Image);
Gray=medfilt2(Image,[3 3]);
figure, imshow(Gray)
Folder = 'C:\Users\alexk\Desktop\Μεταπτυχιακη\image creation';
File = 'gray1.png';
% Write to disk.
imwrite(medfilt2(Image,[3 3]) , fullfile(Folder,File));
%[Pic,rect] = imcrop(Gray);
[Pic, rect] = imcrop(Gray, [1 1 400 400 ]);
figure, imshow(Pic)
File = 'imadjust403.png';
% Write to disk.
imwrite(imadjust(Pic), fullfile(Folder,File));
figure, imhist(Pic)
Black=im2bw(Pic, 0.3);
figure, imshow(Black)
File = 'im2bw403.png';
% Write to disk.
imwrite(im2bw(Pic, 0.3), fullfile(Folder,File));
[n, r] = boxcount(Black)
loglog(r, n,'bo-', r, (r/r(end)).^(-2), 'r--')
legend('real box-count','space-filling box-count');
figure,boxcount(Black, 'slope')
df = -diff(log(n))./diff(log(r));
disp(['Fractal dimension, Df = ' num2str(mean(df(4:8))) ' +/- ' num2str(std(df(4:8)))]);

Accepted Answer

Benjamin Kraus
Benjamin Kraus on 3 Dec 2020
Edited: Benjamin Kraus on 3 Dec 2020
You need to add a for loop, and update the filename based on the level, so you don't overwrite the same file. In the example below I used sprintf to create the filename, but there are tons of other options.
for level = [0.3 0.4 0.5 0.6 0.7]
figure, imhist(Pic)
Black=im2bw(Pic, level);
figure, imshow(Black)
File = sprintf('im2bw403_%0.1f.png', level);
imwrite(im2bw(Pic, 0.3), fullfile(Folder,File));
You may optionally want to close the figures when you are done with each loop, to prevent tons of figures being left behind when the script is done.
% Start of loop
f = figure;
% ... Other code
% End of loop
Benjamin Kraus
Benjamin Kraus on 3 Dec 2020
This thread has drifted away from your original question, and has basically turned into a different question entirely. If my answer to your first question has solved your original problem, I think your best bet is to accept this answer, and then post a new question if you run into any further issues.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!