MATLAB: How to make the process of reading images from the folder, be automatic

automatic;from folderimage analysisImage Processing ToolboxMATLABMATLAB Compilerread imagereading

Hello. At this point, I have a program that reads images using the 'imread' function, and then processes them.
My Mission: I want the process of reading images from the folder to be automatic. In the folder (from which the program reads images) there is a picture called 'image1'. I want my program to read it from the folder, process it, and then wait for the next image ('image2'), to be uploaded to the folder. When the program detects that the image has been uploaded to a folder, the program reads it, processes it, and waits for the next image ('image3'), and so on.
I tried to solve the problem on my own, using the following program, and it didn't work. Can anyone help me?
for k = 1:5
jpgFilename = sprintf('image%d.jpg', k);
fullFileName = fullfile('C:\fproject\final_project\', jpgFilename);
if exist(fullFileName, 'file') %if the image exist in the folder
rgbImage = imread(fullFileName);
else
k=k-1;
for count=1:15
%wait 20 seconds to the image
pause(1)
if exist(fullFileName, 'file')
break %Exit this loop (return to the main loop)
end
if count==20 % if after 20 seconds the image not exist in folder
k=k+1;
break %try to read the next image
end
end
figure, imshow(rgbImage)
end

Best Answer

your problem is you're trying to change the value of the loop index k inside the loop.
that doesn't do anything because matlab for loops don't work like a traditional for loop does (in C, C++, C#, Java, JS, whatever language you know), instead, it sets i to the next value in the loop vector each iteration (ehm foreach loop)
look here:
x = [];
for i = 1:10
x = [x i];
% try to skip number 6
if i == 5
i = 7;
end
end
disp(x);
1 2 3 4 5 6 7 8 9 10
so instead of skiping i = 6 as expected, it simply ignores the fact that we changed i inside the loop and the output of this loop is the entire array.
The answer to your question is just use a while loop (there were a few other issues with your code, I cleaned it up a bit):
waitMax = 20;
k = 1;
while k < 6
jpgFilename = sprintf('image%d.jpg', k);
fullFileName = fullfile('C:\fproject\final_project\', jpgFilename);
if exist(fullFileName, 'file') %if the image exist in the folder
rgbImage = imread(fullFileName);
figure, imshow(rgbImage)
else
for count=1:waitMax
%wait 20 seconds to the image
pause(1)
if exist(fullFileName, 'file')
k=k-1;
break; %Exit this loop (return to the main loop)
end
end
end
k=k+1;
end
Related Question