Load a sequence of images into matlab

I have implemented the following script probably every time I need to load a bunch of images into matlab. This time, I am going to save it for the future:)

%// list all the files in some folder
somefolder = '~/Images/';
filelist = dir(somefolder);
images = [];
%// the first two in filelist are . and ..

count = 1;
for i=3:size(filelist,1)
    %// filelist is not a folder
    if filelist(i).isdir ~= true
        fname = filelist(i).name;
        %// if file extension is jpg
        if strcmp( fname(size(fname,2)-3:size(fname,2)) ,'.jpg'  ) == 1
            tmp = imread([somefolder fname]);
            %// convert it to grayscale image if tmp is a color
            %// image/picture
            if size(tmp,3) == 3
            tmp = rgb2gray(tmp);
            %//resize of image
            %tmp = imresize(tmp,[320 240],'bilinear');
            %// put it into images buffer
            images(:,:,count) = tmp;
            count = count +1;
            %images = [images tmp];
            disp([fname ' loaded']);



26 Responses to Load a sequence of images into matlab

  1. Luis says:


    Thank you very much. It is very useful. I have been searching for it for long time.

    Thanks Again

  2. Rachel says:

    I’m an undergrad at UCSB, and I’ve taken an interest in image processing. I’m starting to play around with images in Matlab, and recently attempted to load multiple images. I’m glad I came across your code, but I don’t really understand it. Would you mind explaining to me how it works?


    • chi3x10 says:

      which part do you not understand?

      you can pretty much ignore everything except the first line inside the most inner if statement. Basically, what i did was first do a “dir” to get a list of all files. Then I used a for loop to iterate through the filelist. If the file is not a folder and if the file extension is “.jpg”, I opened the file and then processed it.

      After I posted this, I found out that instead of using filelist = dir(somefolder); you can do filelist = dir( [somefolder ‘/*.jpg’); With this statement, the filelist will only contain “files” with extension “.jpg”.

      Hope this help.

  3. vinh says:

    Sorry, I am just a newbie with Matlab, I just wanna ask you if it is possible to load sequence of rgb images

  4. ruddi says:

    Hi I made a similar code , but I found a problem with images sequences larger than 100 frame. The imread function doesn’t work with 101 frame and more
    Do you have the same problem or you don’t
    thank you

  5. sebik says:


    it is nice code and very useful, thank you! To ruddi: I have 102 frames and it works without problem.

  6. Krithika Mohan says:

    Hi, I used the code above for loading a sequence of images , but this is the error that I get

    ??? Subscripted assignment dimension mismatch.

    Error in ==> imagesequencereading at 21

    Changing this line to images=tmp; makes the code to work with out syntax errors but I am not able to access a particular frame.

    Could someone ps help me debugging this

  7. This code is working Properly..Thanks for sharing your knowledge……….

    for i=3:size(filelist,1)
    if filelist(i).isdir ~=true

    if strcmp(fname(size(fname,2)-3:size(fname,2)),’.jpg’)==1
    tmp=imread([somefolder fname]);
    if size(tmp,3)==3;


    %images=[images tmp];

    • Ann Shehara says:

      I’m new to the matlab,I want to check the images in a folder one by with a given image can i know how can i use this coding to that purpose…..
      could you help me………………..

  8. zsj says:

    thank you very much,its useful for me

  9. savda says:

    Thanks you very much Rasika Attanayake/Kosala Kuruppu.
    it work well.

  10. zahra says:

    thanks a lot,
    It gives me the hope to countinue coding

  11. yanfeiwang says:

    Hello,the programe is very usefull and it also works well on my computer.Thank you very much! But would you explain how this clause img=dicomread([filefolder fname])works? I mean I can’t understand how does the []works although I can understand how to use the clause.Thanks again!

  12. Akhil Naru says:

    Very Useful. Just what I needed! Thanks

  13. subathira says:

    plz tell me how to execute this code

  14. Ahmed says:

    Hi every one I have project in eye tracking system to be used in safety car and I capture a sequence of images I want to take difference of it but I can not got the code that will help so please I need some help
    thank you

  15. bavithra says:

    Hi i have matlab code for exemplar based image in inpainting algorithrm but for me this program is not running could u help me to run thiis program
    function [inpaintedImg,origImg,fillImg,C,D,fillMovie] = inpaint(imgFilename,fillFilename,fillColor)
    %INPAINT Exemplar-based inpainting.
    % Usage: [inpaintedImg,origImg,fillImg,C,D,fillMovie] …
    % = inpaint(imgFilename,fillFilename,fillColor)
    % Inputs:
    % imgFilename Filename of the original image.
    % fillFilename Filename of the image specifying the fill region.
    % fillColor 1×3 RGB vector specifying the color used to specify
    % the fill region.
    % Outputs:
    % inpaintedImg The inpainted image; an MxNx3 matrix of doubles.
    % origImg The original image; an MxNx3 matrix of doubles.
    % fillImg The fill region image; an MxNx3 matrix of doubles.
    % C MxN matrix of confidence values accumulated over all iterations.
    % D MxN matrix of data term values accumulated over all iterations.
    % fillMovie A Matlab movie struct depicting the fill region over time.
    % Example:
    % [i1,i2,i3,c,d,mov] = inpaint(‘bungee0.png’,’bungee1.png’,[0 255 0]);
    % plotall; % quick and dirty plotting script
    % close; movie(mov); % grab some popcorn
    % author: Sooraj Bhat

    warning off MATLAB:divideByZero [img,fillImg,fillRegion] = loadimg(‘bungee0.png’,’bungee1.png’,’bungeeA.png’);
    img = double(img);
    origImg = img;
    ind = img2ind(img);
    sz = [size(img,1) size(img,2)];
    sourceRegion = ~fillRegion;

    % Initialize isophote values
    [Ix(:,:,3) Iy(:,:,3)] = gradient(img(:,:,3));
    [Ix(:,:,2) Iy(:,:,2)] = gradient(img(:,:,2));
    [Ix(:,:,1) Iy(:,:,1)] = gradient(img(:,:,1));
    Ix = sum(Ix,3)/(3*255); Iy = sum(Iy,3)/(3*255);
    temp = Ix; Ix = -Iy; Iy = temp; % Rotate gradient 90 degrees

    % Initialize confidence and data terms
    C = double(sourceRegion);
    D = repmat(-.1,sz);

    % Visualization stuff
    if nargout==6
    origImg(1,1,:) = fillColor;
    iter = 2;

    % Seed ‘rand’ for reproducible results (good for testing)

    % Loop until entire fill region has been covered
    while any(fillRegion(:))
    % Find contour & normalized gradients of fill region
    dR = find(conv2(fillRegion,[1,1,1;1,-8,1;1,1,1],’same’)>0);

    [Nx,Ny] = gradient(~fillRegion);
    N = [Nx(dR(:)) Ny(dR(:))];
    N = normr(N);
    N(~isfinite(N))=0; % handle NaN and Inf

    % Compute confidences along the fill front
    for k=dR’
    Hp = getpatch(sz,k);
    q = Hp(~(fillRegion(Hp)));
    C(k) = sum(C(q))/numel(Hp);

    % Compute patch priorities = confidence term * data term
    D(dR) = abs(Ix(dR).*N(:,1)+Iy(dR).*N(:,2)) + 0.001;
    priorities = C(dR).* D(dR);

    % Find patch with maximum priority, Hp
    [unused,ndx] = max(priorities(:));
    p = dR(ndx(1));
    [Hp,rows,cols] = getpatch(sz,p);
    toFill = fillRegion(Hp);

    % Find exemplar that minimizes error, Hq
    Hq = bestexemplar(img,img(rows,cols,:),toFill’,sourceRegion);

    % Update fill region
    fillRegion(Hp(toFill)) = false;

    % Propagate confidence & isophote values
    C(Hp(toFill)) = C(p);
    Ix(Hp(toFill)) = Ix(Hq(toFill));
    Iy(Hp(toFill)) = Iy(Hq(toFill));

    % Copy image data from Hq to Hp
    ind(Hp(toFill)) = ind(Hq(toFill));
    img(rows,cols,:) = ind2img(ind(rows,cols),origImg);

    % Visualization stuff
    if nargout==6
    ind2 = ind;
    ind2(fillRegion) = 1;
    iter = iter+1;


    % Scans over the entire image (with a sliding window)
    % for the exemplar with the lowest error. Calls a MEX function.
    function Hq = bestexemplar(img,Ip,toFill,sourceRegion)
    m=size(Ip,1); mm=size(img,1); n=size(Ip,2); nn=size(img,2);
    best = bestexemplarhelper(mm,nn,m,n,img,Ip,toFill,sourceRegion);
    Hq = sub2ndx(best(1):best(2),(best(3):best(4))’,mm);

    % Returns the indices for a 9×9 patch centered at pixel p.
    function [Hp,rows,cols] = getpatch(sz,p)
    % [x,y] = ind2sub(sz,p); % 2*w+1 == the patch size
    w=4; p=p-1; y=floor(p/sz(1))+1; p=rem(p,sz(1)); x=floor(p)+1;
    rows = max(x-w,1):min(x+w,sz(1));
    cols = (max(y-w,1):min(y+w,sz(2)))’;
    Hp = sub2ndx(rows,cols,sz(1));

    % Converts the (rows,cols) subscript-style indices to Matlab index-style
    % indices. Unforunately, ‘sub2ind’ cannot be used for this.
    function N = sub2ndx(rows,cols,nTotalRows)
    X = rows(ones(length(cols),1),:);
    Y = cols(:,ones(1,length(rows)));
    N = X+(Y-1)*nTotalRows;

    % Converts an indexed image into an RGB image, using ‘img’ as a colormap
    function img2 = ind2img(ind,img)
    for i=3:-1:1, temp=img(:,:,i); img2(:,:,i)=temp(ind); end;

    % Converts an RGB image into a indexed image, using the image itself as
    % the colormap.
    function ind = img2ind(img)
    s=size(img); ind=reshape(1:s(1)*s(2),s(1),s(2));

    % Loads the an image and it’s fill region, using ‘fillColor’ as a marker
    % value for knowing which pixels are to be filled.
    function [img,fillImg,fillRegion] = loadimgs(imgFilename,fillFilename,fillColor)
    img = imread(imgFilename); fillImg = imread(fillFilename);
    fillRegion = fillImg(:,:,1)==fillColor(1) & …
    fillImg(:,:,2)==fillColor(2) & fillImg(:,:,3)==fillColor(3);

    thank you
    with regards

  16. sonali says:

    thanks a lot for code …….i m searching same code…..can u pls help me for my small project work…i m doing on face detection and recognization method using eigen vector so can u pls provide me code for that……

  17. viji says:

    how to store the folder of images into array and how to calculate the entropy of those array of images and absolute difference between those entropy values

  18. sourabh says:

    thank for code it is very helpfull ,but can you plz tell where the processed images are storing after resizing. And how can we store the resizes image in a particular image

  19. sourabh says:

    How can we store the resized images in a particular folder.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: