1) I have an original directory called "Original_file" that contains several number of images. The code below serves to read those images from the directory, converts them to greyscale, then write them into new directory called "Target_File".
Target_File='modified_images';
mkdir(Target_File);
directory='original_images';
dnames = {directory};
cI = cell(1,1);
c{1} = dir(dnames{1});
cI{1} = cell(length(c{1}),1);
for j = 1:length(c{1}),
cI{1}{j} = double(imread([dnames{1} '/' c{1}(j).name]))./255;
cI{1}{j} = rgb2gray(cI{1}{j});
imwrite(cI{1}{j}, fullfile(Target_File, ['image' num2str(j) '.jpg']));
end
2) From the "Target_File": The code below serves to select randomly a specific number of images and put them in a training file.
Train_images='training_file';
mkdir(Train_images);
ImageFiles = dir('Target_File');
totalNumberOfFiles = length(ImageFiles)-1;
scrambledList = randperm(totalNumberOfFiles);
numberIWantToUse = 5; % for example 5
loop_counter = 1;
for index = scrambledList(1 :numberIWantToUse)
baseFileName = ImageFiles(index).name
str = fullfile('Target_File', baseFileName);
image = imread(str);
imwrite( image, fullfile(Train_images, ['image' num2str(index) '.jpg']));
loop_counter = loop_counter + 1;
end
What I want in this question ?
A) If we consider that we have a directory that contains several number of folders (folder1, folder2, ...., foldern). Each of these folders contains several images. So how can I edit my code in 1) in order to apply the same concept and get a new directory "Target_File" that contains the same number of folders, but each folder becomes containing the greyscale images?
Then, from the Target_File created in A) : I want to select (randomly as in 2)) from each folder in Target_File, a specific number of images and put them in training file, and the remaining images in testing file. This procedure is repeated for all folders in the directory.
So if the directory contains 3 folders, each of these folders is split into training and test files. So the first folder is split into train1 and test1, the second directory into train2 and test2, the third directory into train3 and test3, etc. So how to edit my code in 2) ?
Any help will be very appreciated.
You can use the dir command to get a list of sub-directories, and then loop through that list with calls to mkdir to create each one in turn. After that, it is just a matter of matching the file paths so you can save the greyscale image loaded from a source subfolder to its corresponding target folder.
Specifically, D = dir('directory') will return a struct where each element of the structure is an element stored in 'directory'. D(i).isdir will be 1 if D(i).name corresponds to the name of one of your subfolders (note that you will need to ignore D(1:2), as those are the folder navigation tags . and ..). So, get your list of directory contents, and then loop through those calling mkdir if D(i).isdir is 1.
I am not sure I understand the rest of your question, but if you just need a random subsample of the entire image set (regardless of subfolder it is stored in), while you are making your subfolders above you can also make secondary calls of dir to the subfolders to get a list of their contents. Loop through and check whether each element is an image, and if it is save it to an array of image path names. When you have compiled this master list, you can grab a random subset from it.
Related
I would like to load different files that have more or less the same just a parameter (temperature) is changing.
For example:
detector_temp = importdata('beginning name file' temp 'K_end name file.dat');
I don't know how to make different "detector" files for all my temperatures.
For the moment I just write all the different file names. I have plenty.
Thank you in advance
Need more information to provide an exact solution but generally you can use dir to get the filenames you want and then load the data into a cell or some other container.
For example say I have a directory of mat files I want to load.
% from the desired directory
files = dir('*.mat'); % get the files I want to load
fileNames = {files.name}'; % extract just the file name
data = cellfun(#load, fileNames, 'UniformOutput', 0); % load all the files into a cell
You can then work on the data that is stored in the cell. Each file is stored in a separate cell. So file1 = data{1,1};, file3 = data{3,1} and so on.
I have a directory with two folders: one folder contains several subfolders with multiple .txt files (folder 1). The second folder contains several .hjson files (folder 2).
I would like load each .txt and .hjson files make a several calculation (e.g. velocity, acceleration, curvature) and save in the same .txt file adding news columns with headers (e.g. velocity, acceleration, curvature). So far, I have one code to load .txt files.
My goal is to make a code that reads, loads, computes and automatically save it. Please let me know if you have any suggestion.
%% Read and load
dir_to_search = 'C:\Programs\pedro\Test\';
txtpattern = fullfile(dir_to_search, '*.txt');
dinfo = dir(txtpattern);
for K = 1 : length(dinfo)
thisfilename = fullfile(dir_to_search, dinfo(K).name); %just the name
thisdata = load(thisfilename); %load just this file
End
You can use fprintf to write to a file.
For example:
formatSpec="%9.5f %8.5f\n";
for i=1:n
fprintf(fid,formatSpec, var1(i),var2(i));
end
I have a lot of folders containing .fig files. Some of these folders contains more than one file which is what I want. The others that only contain one file should get removed with a script.
I thought I could (somehow, I am totally fresh) iterate trough the folders (which exists in one folder will all this other folders) and check if the dir contains more than one file, if not: rmdir(folderName).
Is this possible? Help is very appreciated!
Yes, this is possible through MATLAB
directoryName = 'folderName';
contents = dir(directoryName)
if length(contents) <= 1
rmdir(directoryName);
end
You can also iterate through multiple directories with
files = dir('./');
dirFlags = [files.isdir];
subFolders = files(dirFlags);
for k = 1:length(subFolders)
directoryName = subFolders(k).name;
contents = dir(directoryName);
if length(contents) <= 1
rmdir(directoryName);
end
end
You should probably check that the subFolder is not . or ..
I have a folder dat that could contain n subfolders and these contain various .dat files
I need to get all the files in these subfolder stored in a data structure myarchive that contains the file_name, its subfolder_name and a object resulanalysis that is the result of a my analysis script
The purpose of this operation is to obtain file_name and subfolder_name of the entries in myarchive that matches a generic result
With this code I'm able to get all the analysis result of the files contained in the current folder and I have the matching function, but I don't know how to solve the described classification problem.
files = dir('*.dat');
for file = files'
im = load(file.name);
result=myanalyzer(im);
end
Could someone help me?
If someone has a better strategy that could meet my problem is welcome.
Thanks.
If I understand you correctly, you want to through all the subfolders, load the .dat file, run some analysis and see if the result matches a certain value. If it matches you wan to save the names of the subfolder and the file in a data structure myarchive. If that's the case, here's the code:
topfolder = '...\dat\'; % Specify the full path to the dat folder
cd(topfolder)
subfolderlist = dir;
subfolderlist = subfolderlist(3:end); % because the first two results are '.' and '..'
counter = 0;
for ii = 1:lenght(subfolderlist)
cd([topfolder,subfolderlist(ii).name])
filename = dir('*.dat');
im = load(filename); % assuming there is only one .dat file in the folder
if myanalyzer(im) == result
counter = counter + 1;
myarchive(counter).subfolder_name = subfolerlist(ii);
myarchive(counter).filename = filename;
end
end
I have some 1000 images I need to load as training data for a facial recognition program.
There are 100 people, each have 10 unique pictures.
Saved in a folder like:
myTraining //main folder
- John // sub folder
- John_Smith_001, John_Smith_002, ... , 00n, //images
- Mary // sub folder
- Mary_Someone_001... you get the idea :)
I'm familiar with a lot of matlab but not ways of iterating through external files.
What is an easy implementation to go through each folder, one by one and load the images, ideally using the retrieving the file names and using them as variable/image names.
Thanks in advance.
Using the following commands will recursively list all files in a specific directory and its sub-directories. I have listed it for both Windows and Mac/Linux. I unfortunately can not test the Mac/Linux version since I am not near any of those machines, but it will be fairly similar to what is written below.
Windows
[~,result] = system('dir C:\Users\username\Desktop /a-d /s /b');
files = regexp(result,'\n','Split')
Mac/Linux
[~,result] = system('find /some/Directory -type file);
files = regexp(result,'\n','Split')
You can then iterate through the cell array created, files, and do whatever loading you may need with imread, or something like that
You can do it like this:
basePath = pwd; %your base path which is in your case myTraining
allPaths = dir(basePath); %get all directory content
subFolders = [allPaths(:).isdir]; %get only indices of folders
foldersNames = {allPaths(subFolders).name}'; % filter folders names
foldersNames(ismember(foldersNames,{'.','..'})) = []; %delete default paths for parents return '.','..'
for i=1:length(foldersNames), %loop through all folders
tmp = foldersNames{i}; %get folder by index
p = strcat([basePath '\']);
currentPath =strcat([p tmp]); % add base to current folder
cd(currentPath); % change directory to new path
files = dir('*.jpg'); % list all images in your path which in your case could be John or Mary
for j=1:length(files), % loop through your images
img = imread(files(j).name); % read each image and do what you want
end
end
for jpg images it would be
files = dir('*.jpg');
for file = files'
img = imread(file.name);
% Do some stuff
end
and if you have multiple extensions use
files = [dir('*.jpg'); dir('*.gif')]
I hope this helps