Reading series of images
2 views (last 30 days)
Show older comments
Hi I have the next code:
function Image(ImaIn,ImaFin,coordinates)
for i=ImaIn:ImaFin
I=imread(['DSCN0594 ',num2str(i),'.jpg']);
I2=imcrop(I,coordinates);
imwrite(I2,[num2str(i),'.png'])
end;
This is for reading and cropping the images with the giving coordinates, it functions well. But the problem is that I need to do it for many series. So, the serie DSCN0594 it is not the only I will read and crop and maybe not all the images will be '.jpg' maybe they will be '.png' . I need that this code more flexible. Thank you for your time.
0 Comments
Accepted Answer
Image Analyst
on 24 Jun 2014
Use dir() to get all the possible extensions. Inside your loop over i (bad name by the way), have this code:
baseFileName = sprintf('DSCN0594%d.*', i);
filePattern = fullfile(pwd, baseFileName); % Use whatever folder you want instead of pwd.
allFiles = dir(filePattern);
for k = 1 : length(allFiles)
% Get the full name of the kth file.
thisBaseFileName = allFiles(k).name;
thisFullFileName = fullfile(pwd, thisBaseFileName);
% Read in original image.
originalImage = imread(thisFullFileName);
% Crop it and save cropped version in croppedImage.
croppedImage = imcrop(originalImage, coordinates);
% Save to current folder (which is a bad idea!) with filename
% that depends only on i (again, bad idea).
imwrite(croppedImage, [num2str(i),'.png'])
end
That's just off the top of my head, and not tested, but it should find all versions of the file regardless of whether they are PNG, JPG, TIF, BMP or whatever, and save all of them to the same filename. You might want to change the filename, or save them to the same format as they started with, or else if you have both a PNG and a JPG with the same base file name, the first one will get overwritten.
0 Comments
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!