Hi,
I want to read JPEG images from current directory. Images are named sequentially like image000, image001 and so on. I gave it a try and ended up with following working code:
clc; clear;str = '1820'; filename = 'image1820';X11 = zeros(27648,150);for i = 1:150 % read, convert to grayscale and resize the image
jpegimg = imread(filename,'jpeg'); img2d = rgb2gray(jpegimg); img2d = imresize(img2d,[144 192]); % store image in an array
X11(:,i) = img2d(:); % update string 'str'
str = str2double(str) + 1; str = num2str(str); noofzeros = 4 - length(str); zerostr = ''; for j = 1:noofzeros zerostr = strcat(zerostr,'0'); end str = strcat(zerostr,str); % update filename to be the next file in the folder
filename = strcat('image',str);end
But this code look very crude. I believe there is more elegant and perhaps faster way of doing this. Can you please tell me that 'more elegant and faster' way?
I could have done this in the following way, but 'dir' doesn't seem to work with JPEG images:
fileFolder = fullfile('D:','My Documents');dirOutput = dir(fullfile(fileFolder,'image*','jpeg'));fileNames = {dirOutput.name}';numFrames = numel(fileNames);I = imread(fileNames{1});% Preallocate the array
sequence = zeros([size(I) numFrames],class(I));sequence(:,:,1) = I;% Create image sequence array
for p = 2:numFrames sequence(:,:,p) = imread(fileNames{p}); end
I get the following error when i run this code:
??? Index exceeds matrix dimensions.Error in ==> image_to_vector at 18I = imread(fileNames{1});>>
which is due to the fact that 'dirOutput' is an empty structure:
>> dirOutputdirOutput = 0x1 struct array with fields: name date bytes isdir datenum>>
Thanks!
Best Answer