Remove folder if it contain less than two files - matlab

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 ..

Related

Loop Through Loading Files Error With Same Name

I have a question about how to load in data from multiple directories, but the files I need to load all have the same name. Here's what I have thus far:
for i = 1:numel(smoothlist1) % loop through smoothing directories
path2 = sprintf('%s%s/Trade-off_Curves',path1,smoothlist1(i).name);
cd(path2);
disp(['Changed directories into ', path2]);
data{i} = load('results.xy');
end
I loop through each directory in a list I call smoothlist1.
Within each 'smoothlist1 directory, I change directories into ~/smoothlist1/Curves/. Within this directory, there is a file called results.xy. I need to load each of the results.xy file from each ~smoothlist1/Curves directory, but I am unsure how to do that. What I have above just loads in the final results.xy file in the last smoothlist1/Curves/ directory.
So the question is, how do I loop through loading in that results.xy file from multiple directories? I have tried doing data(j) = results.xy, where I add a counter for j, but that did not work. I would like to load these results.xy files into separate filenames as well.
Thank you for your help.

How to classify elements in a folder and its subfolder in Matlab for matching purposes

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

Iterate through Files, loading images - Matlab

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

Read images from folders in directory

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.

possible to extract files according filename listed in a text file by using matlab?

i have thousand files in a folder, however, i only need to extract out hundred files from the folder according to the filename listed in a text file into new folder. The filenames in text file is listed as a column..is that possible to be run by using matlab?what is the code shall i need to write? Thanks.
example:
filenames.txt is in the C:\matlab
folder include thousand files is named as BigFiles also in C:\matlab
files to be extracted from BigFiles folder is listed in column as below:
filenames.txt
a1sndh
sd3rfe
rgd4de
sd5erw
please advise...thanks...
Enumerate all files in a folder of a specific type (if needed) using:
%main directory to process
directory = 'to_process';
%enumerate all files (.m in this case)
files = dir(fullfile(directory,'*.m'));
numfiles = length(files);
fprintf('Found %i files\n',numfiles)
Then you could load the single column using one of the many file I/O functions in Matlab.
Then just loop through all the input names and check it's name against all the read in files (files{i}.name), and if so, move it.
EDIT:
From what I understood, you are looking for a solution along the lines:
filenames.txt
a.txt
b.txt
c.txt
.
.
.
moveMyFiles.m
%# read filenames listed in a text file
fid = fopen('C:\matlab\filenames.txt');
fList = textscan(fid, '%s');
fList = fList{1};
fclose(fid);
%# source/destination folder names
sourceDir = 'C:\matlab\BigFiles';
destDir = 'C:\matlab\out';
if ~exist(destDir,'dir')
mkdir(destDir);
end
%# move files one by one
for i=1:numel(fList)
movefile(fullfile(sourceDir,fList{i}), fullfile(destDir,fList{i}));
end
You can replace the MOVEFILE function by COPYFILE if you simply want to copy the files instead of moving them...