I have a folder (new_images) which contains 52 sub-folders (person1 to person52) and each sub-folders contain 50 images which are not sequential (like: person1 1, person1 3, person1 10). I want to these read images from each sub-folders and do a processing, How can I do this?
I would really appreciate your answers
You can load images using the Matlab imread function.
I'm thinking of a quick way to do that:
new_images_rep = pwd;
for i=1:52
eval(srcat('pics = dir(new_images_rep','/person',num2str(i),')');
for k=1:50
a(i,k) = imread(pics(k+2).name,'fmt'); %there is k+2 because the dir function also stores repositories like '.' or '..'.
end
end
You have to be careful with the dir function. You should test it in your new_images repository in order to see what are the files/repositories stored in pics.
eval is a Matlab function that allows you to execute any Matlab expression. The string created by strcatis here (if i=3):
'pics = dir(new_images_rep/person3)'
Be sure that the new_imagesrepository is in your Matlab path, or replace new_images_rep = pwd; by new_images_rep = 'the_actual_full_path'.
'fmt' is the actual format of the images you want to store (like .tif or .jpg or anything else).
Using the code I gave you (and a few modifications), all the files from the first subfolder will be stored in a(1,:). Do not hesitate to read Matlab help on every function used here.
Related
I have a folder of images saved as .mat files files with the following names:
image-001-001.mat,image-001-002.mat,......., image-001-102.mat, image-002-001.mat,image-002-002.mat, ....,image-002-090.mat, etc.
I want to group the file names for each prefix. For example, list down all files that starts with image-001- prefix and list all images with image-002- and etc. for all files in the folder. I need the images of each group separately and do some processing on them.
Could someone please give some hints how can I do it?
Thanks in advance
See the documentation for dir, specifically the mention of wildcards.
You can get a list of .mat files which start with image-001 using
files_001 = dir('C:\myfolder\image-001*.mat');
% or if it's in the current directory then simply
% files_001 = dir('image-001*.mat');
To loop over several prefixes, you could use
prefixes = {'image-001', 'image-002', 'image-003'};
files = cell(numel(prefixes), 1);
for p = 1:numel(prefixes)
files{p} = dir([prefixes{p}, '*.mat']);
end
Aside:
If your prefixes really are that similar / ordered, there are many ways (e.g. using strcat) to quickly make the prefixes cell array.
YOu can pick all the images with start with image-001-xxx.mat as below:
files1 = dir('image-001*') ;
I want to read multiple files from a folder but this code does not work properly:
direction=dir('data');
for i=3:length(direction)
Fold_name=strcat('data\',direction(i).name);
filename = fullfile(Fold_name);
fileid= fopen(filename);
data = fread (fileid)';
end
I modified your algorithm to make it easier
Just use this form :
folder='address\datafolder\' ( provide your folder address where data is located)
then:
filenames=dir([folder,'*.txt']); ( whatever your data format is, you can specify it in case you have other files you do not want to import, in this example, i used .txt format files)
for k = 1 : numel(filenames)
Do your code
end
It should work. It's a much more efficient method, as it can apply to any folder without you worrying about names, number order etc... Unless you want to specify certain files with the same format within the folder. I would recommend you to use a separate folder to put your files in.
In case of getting access to all the files after reading:
direction=dir('data');
for i=3:length(direction)
Fold_name=strcat('data\',direction(i).name);
filename = fullfile(Fold_name);
fileid(i)= fopen(filename);
data{i-2} = fread (fileid(i))';
end
So I have a directory that has many .mat files:
apples.mat, oranges.mat, bananas.mat, grapes.mat, apricots.mat, pears.mat, pineapple.mat
All of these .mat files has a variable name "calories" assigned a value. How do I load all of these .mat files simultaneously in MATLAB and change the variables for each one from calories to calories_(fruit name) so that I can have all the variable values in the workspace to play with?
For example, I want to load apples.mat and change its variable name from calories to calories_apple, then load oranges.mat and change is variable name from calories_orange, etc. without doing it all manually.
I know it's something along the lines of creating a string with the different fruit names, and the indexing along the string to load a file and change its variable from variable to variable_%s with the %s indicating the fruit content generated along the loop. It's a big mess for me, however, I don't think I'm structuring it right. Would anyone care to help me out?
I would load each .mat file in sequence and put each of the corresponding calories as a separate field being all combined into a single struct for you to access. Given the directory of where these .mat files appear, do something like this:
%// Declare empty structure
s = struct()
folder = '...'; %// Place directory here
%// Get all MAT files in directory
f = dir(fullfile(folder, '*.mat'));
%// For each MAT file...
for idx = 1 : numel(f)
%// Get absolute path to MAT file - i.e. folder/file.mat
name = fullfile(folder, f(idx).name);
%// Load this MAT file into the workspace and get the calories variable
load(name, 'calories');
%// Get the name of the fruit, are all of the characters except the last 4 (i.e. .mat)
fruit_name = f(idx).name(1:end-4);
%// Place corresponding calories of the fruit in the structure
s.(['calories_' fruit_name]) = calories;
end
You can then access each of the calories like so using dot notation:
c = s.calories_apple;
d = s.calories_orange;
...
...
... and so on.
I am assuming that you do not mean to include the parenthesis in calories_(fruit name). I am also assuming there are no other .mat files in your current directory. This should do the trick:
theFiles = dir('*.mat');
for k = 1:length(theFiles)
load(theFiles(k).name, 'calories');
eval(['calories_' theFiles(k).name(1:length(theFiles(k).name)-4) ' = calories;'])
clear calories
end
Let me know if this helps or not.
EDIT
As, rayryeng points out. The use of eval is, apparently, a bad practice. So, if you are willing to change the way you are thinking about the problem, I suggest you use a structure. In which case, rayryeng's response would be an acceptable answer, even though it does not directly answers your original question.
I have several data log files (here: 34) for those I have to calculate some certain values. I wrote a seperate function to publish the results of the calculation in a pdf file. But I only can publish one file after another, so it takes a while to publish all 34 files.
Now I want to automize that with a loop - importing the data, calculate the values and publish the results for every log file in a new pdf file. I want 34 pdf files for every log file at the end.
My problem is, that I couldn't find a way to rename the pdf files during publishing. The pdf file is always named after the script which is calculating the values. Obviously the pdf is overwritten within a loop. So at the end everything is calculated, but I only have the pdf from the last calculated log file.
There was this hacky solution to change the Matlab publish script, but since I don't have admin rights I can't use that:
"This is really hacky, but I would modify publish to accept a new option prefix. Replace line 93
[scriptDir,prefix] = fileparts(fullPathToScript);
with
if ~isfield(options, 'prefix')
[scriptDir,prefix] = fileparts(fullPathToScript);
else
[scriptDir,~] = fileparts(fullPathToScript);
prefix = options.prefix; end
Now you can set options.prefix to whatever filename you want. If you want to be really hardcore, make the appropriate modifications to supplyDefaultOptions and checkOptionFields as well."
Any suggestions?
Thanks in advance,
Martin
Here's one idea using movefile to rename the resultant published PDF on each iteration:
for i = 1:34
file = publish(files(i)); % Replace with your own command(s)
[pathStr,fileName,ext] = fileparts(file);
newFile = [pathStr filesep() fileName '_' int2str(i) ext]; % Example: append _# to each
[success,msg,msgid] = movefile(file,newFile);
if ~success
error(msgid,msg);
end
end
Also used are fileparts and filesep. See this question for other ways to rename and move files.
I have 4 folders in the same directory where each folder contains ~19 .xls files. I have written the code below to obtain the name of each of the folders and the name of each .xls file within the folders.
path='E:\Practice';
folder = path;
dirListing = dir(folder);
dirListing=dirListing(3:end);%first 2 are just pointers
for i=1:length(dirListing);
f{i} = fullfile(path, dirListing(i,1).name);%obtain the name of each folder
files{i}=dir(fullfile(f{i},'*.xls'));%find the .xls files
for j=1:length(files{1,i});
File_Name{1,i}{j,1}=files{1,i}(j,1).name;%find the name of each .xls file
end
end
Now I'm trying to import the data from excel into matlab by using xlsread. What I'm struggling with is knowing how to load the data into matlab within a loop where the excel files are in different directories (different folders).
This leaves me with a 1x4 cell named File_Name where each cell refers to a different folder located under 'path', and within each cell is then the name of the spreadsheets wanting to be imported. The size of the cells vary as the number of spreadsheets in each folder varies.
Any ideas?
thanks in advance
I'm not sure if I'm understanding your problem, but all you have to do is concatenate the strings that contain directory (f{}) and the file name. Modifying your code:
for i=1:length(dirListing);
f{i} = fullfile(path, dirListing(i,1).name);%obtain the name of each folder
files{i}=dir(fullfile(f{i},'*.xls'));%find the .xls files
for j=1:length(files{1,i});
File_Name{1,i}{j,1}=files{1,i}(j,1).name;%find the name of each .xls file
fullpath = [f{i} '/' File_Name{1,i}{j,1}];
disp(['Reading file: ' fullpath])
x = xlsread(fullpath);
end
end
This works on *nix systems. You may have to join the filenames with a '\' on Windows. I'll find a more elegant way and update this posting.
Edit: The command filesep gives the forward or backward slash, depending on your system. The following should give you the full path:
fullpath = [f{i} filesep File_Name{1,i}{j,1}];
Take a look at this helper function, written by a member of the matlab community.
It allows you to recursively search through directories to find files that match a certain pattern. This is a super handy function to use when looking to match files.
You should be able to find all your files in a single call to this function. Then you can loop through the results of the rdir function, loading the files one at a time into whatever data structure you want.