Reading series of images

1 次查看(过去 30 天)
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.

采纳的回答

Image Analyst
Image Analyst 2014-6-24
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 个)

类别

Help CenterFile Exchange 中查找有关 Video games 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by