MATLAB Answers

0

How to read all types images from the folder regardless of file extension ?

Asked by Renjith V Ravi on 31 Oct 2017
Latest activity Commented on by Walter Roberson
on 21 Mar 2019
The below is my code
clear all
close all
clc
Directory = 'Images_folder\';
% Read images from Images folder
Imgs = dir(fullfile(Directory,'*.bmp'));
for j=1:length(Imgs)
Img = imread(fullfile(Directory,Imgs(j).name)); % Read image
Im = Img(:,:,1);
figure
imshow(Im)
end
From this code I can read only .bmp images.But I want to read all types of images from the folder regardless of the file extension.

  0 Comments

Sign in to comment.

Tags

2 Answers

Answer by Walter Roberson
on 31 Oct 2017
 Accepted Answer

Directory = 'Images_folder';
% Read images from Images folder
Imgs = dir(Directory);
for j=1:length(Imgs)
thisname = Imgs(j).name;
thisfile = fullfile(Directory, thisname);
try
Img = imread(thisfile); % try to read image
Im = Img(:,:,1);
figure
imshow(Im)
title(thisname);
catch
end
end
Remember, image files are defined by their content, not by their extension, so the only sure way to determine if any given file can be read as an image is to try reading it as an image.
Myself, I would at the very least filter out directories before making the attempt, but I do not know Windows well enough to be certain that it would refuse to read a directory as an image.
This code is deficient in that it can only read the image types handled by MATLAB, not all types of images as you had asked for.

  1 Comment

Sign in to comment.


Answer by KSSV
on 31 Oct 2017

Files=[dir('*.jpg');dir('*.png')]
specify all possible image extensions.

  7 Comments

what happened when you tried the code in my answer ?
actually, total 20 images are in my folder, after executing the code 'Imgs' contains 22 contents and extra two are dummy (nothing is present). but i need exactly 20 images of various formats.
In my code, Imgs (capital I) will contain directory information for everything in the folder, including the . and .. folders. It is the loop with the try/catch that determines whether each entry is an image file that MATLAB is able to deal with, so you should record the filename information for those cases.
It is easier when there are a list of specific extensions you want to be able to handle, instead of wanting "everything that MATLAB turns out to be able to process" no matter how obscure.

Sign in to comment.