Reading images from folder one by one - matlab

I have a folder that has various images I am trying to read images in a loop from folder one by one using imread command, any suggestion how to do it best
Thanks

You can use the dir function to get all files inside a directory. This will return a vector of structs which also includes the filenames
loop over all structs
check if file is an image (check e.g. extension)
read image

You have to synchronize your image names to read in a loop. They have to be like image1.jpg, image2.jpg, image3.jpg... You have 10 images like this.
NumberOfimages=10; %chose the number of images you want to give input
prefix_image='image'; %change the desired input image name here only
fileformat='.jpg'; %change the desired input image format here only
for num=1:NumberOfimages
image = imread(strcat(prefix_image,num2str(num),fileformat));
end

well this function will help you to read many images at once even with diferent names:
First put all your images in a folder for example: D:/lab/
they must be in the same format for example: tif
to call the function you type :
A=imread_many( );
and all the images will be in the variable A
if you want the first image you type A{1} if u want the second u type A{2} ..etc
function [ A ] = imread_many( )
srcFiles = dir('D:\lab\*.tif'); % the folder in which ur images exists
for i = 1 : length(srcFiles)
filename = strcat('D:\lab\',srcFiles(i).name);
A{i} = imread(filename);
figure, imshow(A{i});
end
end

srcFiles = dir('C:\Users\Omm\Downloads\multicharacterrec\*.png'); % the folder in which ur images exists
for i = 1 : length(srcFiles)
filename = strcat('C:\Users\Omm\Downloads\multicharacterrec\',srcFiles(i).name);
I = imread(filename);
figure, imshow(I);

This can Help !
S = struct2cell(dir('*.jpg'));
FileNames = S(1,:);
lenDb = length(FileNames);
result= struct('img', {});
for j = 1 : lenDb
result(j).img = imread(FileNames{j})
end
All the images are in struct "result.img"
To have access just call result(NUM).img
Ex:
image(result(1).img)

Related

Batch process and name/save images in a separate folder

I am running a script to create masks of 41 Controls, both Positive and Negative, for a total of 82 images. I don't know how to save the masks with names similar to the original .png files, such as "Masked Control_1 Positive", "Masked Control_1 Negative", etc to Control_41. I also don't know how to save these to a separate folder within my current folder. Thank you!
I have also included a screenshot of the current directory.
% GlassBrains_Controls2Mask.m
clear;
Files = dir('Control_*');
Controls_Results_Structure = struct('BW',[],'maskedRGBImage',[]);
for i = 1:length(Files)
RGB = imread(Files(i).name);
[Output_BW, Output_maskedRGBImage] = GlassBrainMask(RGB);
Controls_Results_Structure(i).BW = Output_BW;
Controls_Results_Structure(i).maskedRGBImage = Output_maskedRGBImage;
end
save("Controls_Results_Structure")
% Save the results
mkdir "Masked Glass Brains (Controls)"
for i = 1:length(Files)
Image_Number = i;
save(Controls_Results_Structure(Image_Number).BW);
end
Please notice that save() stores workspace variables in MAT files, which are generally meant to be opened with MATLAB only, not with image viewers and such. PNG files like those you are reading with imread() can be created with imwrite():
% Save the results
outdir='./Masked Glass Brains (Controls)';
[mkdir_status,~,~]=mkdir(outdir);
assert(mkdir_status,'Error creating output folder.');
clear mkdir_status;
for i=1:length(Files)
imwrite( Controls_Results_Structure(i).BW, ...
sprintf('%s/Masked %s',outdir,Files(i).name) ... %alternative: [outdir '/Masked ' Files(i).name]
);
end
To customize the image file that imwrite() creates from the output of GlassBrainMask(), see: https://www.mathworks.com/help/matlab/ref/imwrite.html

Recursively read images from subdirectories

I am stuck on something that is supposed to be so simple.
I have a folder, say main_folder with four sub folders, say sub1, sub2, sub3 and sub4 each containing over 100 images. Now am trying to read and store them in an array. I have looked all over the internet and some MATLAB docs:
here, here and even the official doc.
My code is like this:
folder = 'main_folder/**'; %path containing all the training images
dirImage = dir('main_folder/**/*.jpg');%rdir(fullfile(folder,'*.jpg')); %reading the contents of directory
numData = size(dirImage,1); %no. of samples
arrayImage = zeros(numData, 133183); % zeros matrix for storing the extracted features from images
for i=1:numData
ifile = dirImage(i).name;
% ifolder = dirImage(i).folder;
I=imread([folder, '/', ifile]); %%%% read the image %%%%%
I=imresize(I,[128 128]);
...
If I try the code in the above snippet, the images are not read.
But if I replace the first two lines with something like:
folder = 'main_folder/'; %path containing all the training images
dirImage = dir('main_folder/sub1/*.jpg'); %rdir(fullfile(folder,'*.jpg'));
then all images in sub1 are read. How can I fix this? Any help will be highly appreciated. I want to read all the images in the four sub folders at once.
I am using MATLAB R2015a.
I believe you will need to use genpath to get all sub-folders, and then loop through each of them, like:
dirs = genpath('main_folder/'); % all folders recursively
dirs = regexp(dirs, pathsep, 'split'); % split into cellstr
for i = 1:numel(dirs)
dirImage = dir([dirs{i} '/*.jpg']); % jpg in one sub-folder
for j = 1:numel(dirImage)
img = imread([dirs{i} '/' dirImage(j).name]);
% process img using your code
end
end

store multi images in mat file using matlab

The bellow matlab code is to read 6 images from folder and save them in mat file
then return to read the mat file and check the images inside it
the problem is that
just the last images stores in mat file
the problem is in save function::
what should I edit to make save function store all images that stored in result cell into mat file
%Generate mat file
srcFile = dir('C:\Users\Desktop\images\*.jpg');
result = cell(1,length(srcFile));
for i = 1 : length(srcFile)
filename = strcat('C:\Users\Desktop\images\',srcFile(i).name);
I = imread(filename);
%figure, imshow(I);
I = imresize(I,[128 128]);
result{i} = I;
figure, imshow(result{i});
end
save images, result;
%Read mat file
for j =1 :length(srcFile)
filename = strcat('C:\Users\Desktop\images\',srcFile(j).name);
I = imread(filename);
a='I';
input = load('images.mat',a);
figure, imshow(input.(a));
end
Your first loop, up to the save, is fine.
When you load the data, use load('images.mat') before the second loop. Then, you have back the result variable in your workspace and you iterate on it:
load('images.mat')
for j = 1:length(srcFile)
figure, imshow(result{j});
end
What you have to remember is that your .mat file only contains the variables you saved, but you can't access them directly with load. You first load them, and then access the loaded variables (which have a different name from the file, usually).
Finally, if you want to check this code, you need to clear the workspace after the save, otherwise you may not notice that some of the variables you use are not there anymore (like the error you have got with I).

How to read multiple jpg images in matlab [duplicate]

I have certain images in a directory and I want to load all those images to do some processing. I tried using the load function.
imagefiles = dir('F:\SIFT_Yantao\demo-data\*.jpg');
nfiles = length(imagefiles); % Number of files found
for i=1:nfiles
currentfilename=imagefiles(i).name;
I2 = imread(currentfilename);
[pathstr, name, ext] = fileparts(currentfilename);
textfilename = [name '.mat'];
fulltxtfilename = [pathstr textfilename];
load(fulltxtfilename);
descr2 = des2;
frames2 = loc2;
do_match(I1, descr1, frames1, I2, descr2, frames2) ;
end
I am getting an error as unable to read xyz.jpg no such file or directory found, where xyz is my first image in that directory.
I also want to load all formats of images from the directory instead of just jpg...how can i do that?
You can easily load multiple images with same type as follows:
function Seq = loadImages(imgPath, imgType)
%imgPath = 'path/to/images/folder/';
%imgType = '*.png'; % change based on image type
images = dir([imgPath imgType]);
N = length(images);
% check images
if( ~exist(imgPath, 'dir') || N<1 )
display('Directory not found or no matching images found.');
end
% preallocate cell
Seq{N,1} = []
for idx = 1:N
Seq{d} = imread([imgPath images(idx).name]);
end
end
I believe you want the imread function, not load. See the documentation.
The full path (inc. directory) is not held in imgfiles.name, just the file name, so it can't find the file because you haven't told it where to look. If you don't want to change directories, use fullfile again when reading the file.
You're also using the wrong function for reading the images - try imread.
Other notes: it's best not to use i for variables, and your loop is overwriting I2 at every step, so you will end up with only one image, not four.
You can use the imageSet object in the Computer Vision System Toolbox. It loads image file names from a given directory, and gives you the ability to read the images sequentially. It also gives you the option to recurse into subdirectories.

concatenate matrix to another matrix

I wrote a matlab code that reads images from folder(images are in RGB). It reads the image one by one. After reading the first image it re-sizes it and then reshapes it so that the new image dimension is (any number of rows X 3 volumes) using this function:
Vectrgb = reshape(rgb,[],3);
Then the code will read a new image.
How should I append the matrix of the second image to the one?
Below is the code:
Folder = 'fo\';
Files = dir([Folder, '\*.png']);
Y=[];
for i = 1 : length(Folder)
name = strcat('telo-phase\',Files(i).name);
image = imread(name);
rgb = imresize(image, 0.50); % resize the image
Vectrgb = reshape(rgb,[],3);
end
Vectrgb1 = Vectrgb';[ind2,ctrs2]= kmeans(double(Vectrgb1),2);
If you wat Y to be the concatanation of all RGB vectors of all images you need to add this line inside the loop
Y = cat( 1, Y, Vecrgb );
PS,
When dealing with filenames and paths it is a good practice to use fullfile command:
Files = dir( fullfile( Folder, '*.png' ) );
Makes your code platform independent.