Overwritting problem in for loop
이전 댓글 표시
I simply crop images and save them with a number.For example i have Grain #1,Grain #2,Grain #3.If i move to another image and crop further images i cannot create images Grain #4 ,Grain #5 etc and instead there are overwritten images...Here is my code.Where is my mistake??
clear all;
clc;
addpath(genpath('C:\Users\User\Desktop\TEI'));
imtool close all;
k=input('How many times do you want to repeat the cropping?');
IMAGE = uigetfile('*.jpg','Pick an image');
A=imread(IMAGE);
figure,imshow(IMAGE);
folder=('C:\Users\User\Desktop\TEI\BEE_POLLEN _PROJECT\Scripts');
for i=1:k
f = sprintf('Select a ROI and double click to crop #%d',i);
uiwait(warndlg(f));
[B, rect] = imcrop(A);
baseFileName = sprintf('Grain #%d.jpg',i);
fullFileName = fullfile(folder, baseFileName);
baseFileName2 = sprintf('Grain #%d .jpg', (i+1));
fullFileName2 = fullfile(folder, baseFileName2);
if exist(fullFileName)
imwrite(B, fullFileName2);
else
imwrite(B, fullFileName);
end
if i==k
f=sprintf('FINISHED!!');
uiwait(warndlg(f));
end
end
댓글 수: 4
dpb
2019년 3월 16일
You base the file number on the 1:k loop index variable i so it starts all over from the beginning every time you run the script.
You would need to keep a persistent variable that retains its value to continue numbering from the last case to just keep making more files of the same base name.
BUT, I'd suggest you should probably go to a more expressive naming scheme where you build a name for the set of cropped image files for a given input image that reflects that input file as well as just a sequence number.
Also, when you create sequentially-numbered files such as this, unless it is absolutely certain that there will never be more than 1 thru 9 for a given base name, you shoule use a format that writes leading zeros for the numeric part -- otherwise they will not sort numerically, but alphabetically.
fmt='Grain #%03d.jpg' ;
baseFileName = sprintf(fmt,i);
DIMITRIOS THEODOROPOULOS
2019년 3월 16일
dpb
2019년 3월 16일
At least give it a go with the supplied hints..."nothing ventured, nothing gained!"
Specific Q? if/when you have a specific problem, sure; just write code for another's job?, "not so much"...
The clear all will impede the method of using a persistent variable. Because this brute clearing of everything has other severe disadvantages also, omitting it is a good idea in general.
Adding a set of folders automatically to Matlab's path can cause problems, when any of the included folders contain M-files:
addpath(genpath('C:\Users\User\Desktop\TEI'));
Do you do this only to access the images in these folders? Then leave the path untouched. You are using absolute file names already, so do not pollute the path without needs.
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!