Thresholding for different values and save all figures automatically
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
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:
clc;
clear all
Image=imread('cu_giannisx1000.tif');
%Image = rgb2gray(Image);
Gray=medfilt2(Image,[3 3]);
figure, imshow(Gray)
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 ]);
Pic=imadjust(Pic);
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)
Label=bwlabel(Black);
File = 'im2bw403.png';
% Write to disk.
imwrite(im2bw(Pic, 0.3), fullfile(Folder,File));
figure,boxcount(Black)
[n, r] = boxcount(Black)
loglog(r, n,'bo-', r, (r/r(end)).^(-2), 'r--')
xlabel('r')
ylabel('n(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)))]);
채택된 답변
Benjamin Kraus
2020년 12월 3일
편집: Benjamin Kraus
2020년 12월 3일
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)
Label=bwlabel(Black);
File = sprintf('im2bw403_%0.1f.png', level);
imwrite(im2bw(Pic, 0.3), fullfile(Folder,File));
end
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
close(f)
댓글 수: 13
thank you so much for the response , but is there a way for each of the figures (for 0.3 up to 0.7) to do the fractal dimension the part of the code that starts with figure,boxcount(Black) till the end automaticaly for each level and save those graphs as well?
Again thank you so muchh for the response
You can export any MATLAB figure to a PNG file (or any other format) using the print command, or in MATLAB R2020a or newer the exportgraphics command.
f = figure;
% Your code to create your desired picture
print(f,'filename','-dpng')
% Alternatively in R2020a or newer
exportgraphics(f,'filename.png')
thank you again for the response i tried this method show my code looks like this now (the for loop part)
for level = [0.3 0.4 0.5 0.6 0.7]
figure, imhist(Pic)
Black=im2bw(Pic, level);
figure, imshow(Black)
Label=bwlabel(Black);
File = sprintf('im2bw403_%0.1f.png', level);
imwrite(im2bw(Pic, level), fullfile(Folder,File));
f = figure;
% Your code to create your desired picture
figure,boxcount(Black)
exportgraphics(f,'box.png')
[n, r] = boxcount(Black)
loglog(r, n,'bo-', r, (r/r(end)).^(-2), 'r--')
xlabel('r')
ylabel('n(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)))]);
exportgraphics(f,'slope.png')
end
but i get an error of this kind
Error using exportgraphics
The value of 'destination' is invalid. Cannot create output file 'box.png'.
Error in aaa (line 42)
exportgraphics(f,'box.png')
I think that means you do not have write permissions to the directory you are trying to write to. In your modified code, you are specifying a file name, but no directory, so the code is trying to export to the current directory.
When you call imwrite you are using fullfile to generate a longer file name (including a folder). You can do the same with exportgraphics (and print).
Note: You are also hard-coding the file name, so each loop will write over the file created in the previous loop. You probably want to dynamically create the file name, using something like sprintf.
For example:
File = sprintf('slope%0.1f.png', level);
exportgraphics(f,fullfile(Folder,File));
Alex, if you highlight your code and click the Code icon, it makes it easy for people to copy your code into the clipboard and run it. Notice how Benjamin's code has a copy icon on it to make it easy for you to copy it? Your can too if you highlight it and click the Code icon on the tool ribbon before you submit your posting.
lena kappa
2020년 12월 3일
편집: lena kappa
2022년 4월 18일
thank you for the tip image analyst i will try that now!!!
this is my code now it runs and saves the pics in the file but when i open them they are blank ...
if you guys have any more tips please tell me
thank you for all your answers up until now!!!
clc;
clear all
Image=imread('2.png');
Image = rgb2gray(Image);
Gray=medfilt2(Image,[3 3]);
figure, imshow(Gray)
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 ]);
Pic=imadjust(Pic);
figure, imshow(Pic)
File = 'imadjust403.png';
% Write to disk.
imwrite(imadjust(Pic), fullfile(Folder,File));
for level = [0.3 0.4 0.5 0.6 0.7]
figure, imhist(Pic)
Black=im2bw(Pic, level);
figure, imshow(Black)
Label=bwlabel(Black);
File = sprintf('im2bw403_%0.1f.png', level);
imwrite(im2bw(Pic, level), fullfile(Folder,File));
f = figure;
% Your code to create your desired picture
figure,boxcount(Black)
File = sprintf('box%0.1f.png', level);
exportgraphics(f,fullfile(Folder,File));
[n, r] = boxcount(Black)
loglog(r, n,'bo-', r, (r/r(end)).^(-2), 'r--')
xlabel('r')
ylabel('n(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)))]);
File = sprintf('slope%0.1f.png', level);
exportgraphics(f,fullfile(Folder,File));
end
what i want to get saved is for example this the figure that i get from the next line of code ... and my code saves something else??? im not sure
disp(['Fractal dimension, Df = ' num2str(mean(df(4:8))) ' +/- ' num2str(std(df(4:8)))]);
Your figures are blank because you are creating multiple figures, exporting before you plot, and exporting the wrong figure.
f = figure;
figure,boxcount(Black)
File = sprintf('box%0.1f.png', level);
exportgraphics(f,fullfile(Folder,File));
[n, r] = boxcount(Black)
loglog(r, n,'bo-', r, (r/r(end)).^(-2), 'r--')
- The first line is creating a figure.
- The second line is creating another figure, then plotting into that figure. I'm not sure what boxcount does.
- The third and fourth lines are exporting the first figure, which is empty.
- The last line is creating a plot in the second figure, but you are exporting the first figure.
I'm not sure if the boxcount command creates an image or not.
- If boxcount creates an image, then you just need to remove the second call to figure.
- If boxcount does not create an image, you need to move exportgraphics to after your figure is finished being created (after your call to legend is my best guess).
thank you so much for your help
i tried to add some lines to write my results in a txt file but i get this error
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
Error in alexevenbetter (line 55)
A = [level; num2str(mean(df(4:8)))];
if you know anything it would be great or anyother way to write the in a .txt file
for level = [0.3 0.4 0.5 0.6 0.7]
figure, imhist(Pic)
Black=im2bw(Pic, level);
figure, imshow(Black)
Label=bwlabel(Black);
File = sprintf('im2bw403_%0.1f.png', level);
imwrite(im2bw(Pic, level), fullfile(Folder,File));
f = figure;
% Your code to create your desired picture
boxcount(Black)
[n, r] = boxcount(Black)
loglog(r, n,'bo-', r, (r/r(end)).^(-2), 'r--')
xlabel('r')
ylabel('n(r)')
legend('real box-count','space-filling box-count');
File = sprintf('box%0.1f.png', level);
exportgraphics(f,fullfile(Folder,File));
boxcount(Black, 'slope')
df = -diff(log(n))./diff(log(r));
disp(['Fractal dimension, Df = ' num2str(mean(df(4:8))) ' +/- ' num2str(std(df(4:8)))]);
File = sprintf('slope%0.1f.png', level);
exportgraphics(f,fullfile(Folder,File));
A = [level; num2str(mean(df(4:8)))];
fileID = fopen('dim.txt','w');
fprintf(fileID,'%6.2f %12.8f\n',A);
fclose(fileID);
end
lena kappa
2020년 12월 3일
편집: lena kappa
2022년 4월 18일
you are absolutely correct i changed it to this but it only saves the last number for leveling and mean(df(4:8)) while i want it t save all of them from 0.3 to 0.7
A = [level; (mean(df(4:8)))];
[fileID, message] = fopen('C:\Users\Desktop\image creation\dim.txt', 'w');
fprintf(fileID,'%f %f\n',A);
fclose(fileID);
When you call fopen you are specifying 'w' which means "Open or create new file for writing. Discard existing contents, if any." Changing that to 'a' will "Open or create new file for writing. Append data to the end of the file." See the doc for fopen for more information.
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.
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Convert Image Type에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
