Life is a game, take it seriously

Posts Tagged ‘images’

MATLAB: Read all images in a folder; everything starts here

In Computer Vision, Matlab on April 13, 2011 at 3:26 pm

written by Gooly

In ordinary people’s life, it’s often the case that you need to deal with a large but not extremely huge image database with non sequential naming. Instead of reading each image when you need it, you probably would prefer to read it all into a matrix for one time, or even store it into a mat file so that you can access it much faster next time. The MATLAB function dir would be a good way to do this, see the example below.

function X = ReadImgs(Folder,ImgType)
    Imgs = dir([Folder '/' ImgType]);
    NumImgs = size(Imgs,1);
    image = double(imread([Folder '/' Imgs(1).name]));
    X = zeros([NumImgs size(image)]);
    for i=1:NumImgs,
      image = double(imread([Folder '/' Imgs(i).name]));
      if (size(image,3) == 1)
        X(i,:,:) = image;
        X(i,:,:,:) = image;

To read in all the jpeg files in image_folder simply do the following,

ImageData = ReadImgs('image_folder','*.jpg');

Notice that this function only deals with image of the same size, which is usually the case; to be able to deal with different size images, you can use imresize in the function or other methods depending on what the task you are actually working on.

When dealing with huge image database (2GB up), you would probably prefer to store the images into separate mat files, only open the one that you want to use, and close it afterwards.

Note that as Thiruvikraman Kandhadai mentioned in the comment, this code won’t run if you have both RGB and Gray scale images in the folder. Save them into two separate matrices if you really need to.