Renaming JPG images in matlab - matlab

I am new to matlab and image analysis. I would really appreciate some insight/help into the following problem. I am trying to rename images (jpg) in a folder that have a random name into specific (new) names. I made the an excel file with two columns the first column contains the old names and the second column the new names. I found the next code on stack overflow (Rename image file name in matlab):
dirData = dir('*.jpg'); %# Get the selected file data
fileNames = {dirData.name}; %# Create a cell array of file names
for iFile = 1:numel(fileNames) %# Loop over the file names
newName = sprintf('image%05d.jpg',iFile); %# Make the new name
movefile(fileNames{iFile},newName); %# Rename the file
end
The code gives all the photos a new name based on the old one but that is not what I want, the new names I use are not linked to the old ones. I tried the following code :
g= xlsread('names.xlsx') % names.xlsx the excel file with old and new names
for i=1:nrows(g)
image=open(g(i,1));
save(g(i,2),image);
end
It doesn't work. I get the error message :using open (line 68)
NAME must contain a single string. I don't think open is the right function to use.
Thank you !

How about this:
% Get the jpeg names
dir_data = dir('*.jpg');
jpg_names = {dir_data.name};
% Rename the files according to the .xlsx file
[~,g,~] = xlsread('names.xlsx'); % Thanks to the post of Sean
old_names = g(:,1);
new_names = g(:,2);
for k = 1:numel(old_names)
% check if the file exists
ix_file = strcmpi(old_names{k}, jpg_names);
if any(ix_file)
movefile(old_names{k}, new_names{k});
end;
end;

It seems like g = xlsread(file) reads only numeric data from file (see here). The third output argument of xlsread returns raw data including strings; does the following work? (i don't have excel and can't test it)
[~, ~, g] = xlsread('names.xlsx')
for i = 1:nrows(g)
movefile(g{i,1}, g{i,2})
end

Related

How to loop through a set of files of varying type in MATLAB

I have a set of files in a folder that I want to convert to a different type using MATLAB, ie. for each file in this folder do "x".
I have seen answers that suggest the use of the "dir" function to create a structure that contains all the files as elements (Loop through files in a folder in matlab). However, this function requires me to specify the file type (.csv, .txt, etc). The files I want to process are from a very old microscope and have the file suffixes .000, .001, .002, etc so I'm unable to use the solutions suggested elsewhere.
Does anyone know how I can get around this problem? This is my first time using MATLAB so any help would be greatly appreciated. All the best!
As suggested by beaker and Ander Biguri, you can do this by getting all files and then sorting.
Here is the related code with explanations inline:
baseDir = 'C:\mydir';
files = dir(baseDir);
files( [ files.isdir] ) = []; % This removes directories, especially '.' and '..'.
fileNames = cell(size(files)); % In this cell, we store the file names.
fileExt = cell(size(files)); % In this cell, we store the file extensions.
for k = 1 : numel(fileNames )
cf = files(k);
fileNames{k} = [ cf.folder filesep cf.name]; % Get file name
[~,~, fileExt{k}] = fileparts( cf.name ); % Get extension
end
[~,idx] = sort( fileExt ); % Get index to sort by extension
fileNames = fileNames( idx ); % Do the actual sorting

Matlab file name concatenation

%% File Names reading and label generation
dataFolder= 'allcontent';
fileNames = dir([dataFolder 'c*.*']);
lbl = sscanf(cat(1,'fileNames.name'),'co2%c%d.rd.%d');
status = lbl(1:3:end);
id = lbl(2:3:end);
ids = unique(id);
trial = lbl(3:3:end);
I want to concatenate the names of all the files in the folder titled all content , at the moment, matlab doesn't understand what allcontent is. Can someone help me get the contents of the folder ' all content' which are of the form 'c*.*' and then concatenate them?
You can use fullfile to concatenate paths in Matlab, i.e.
fileNames = dir(fullfile(dataFolder, 'c*.*'));
Also, I don't think fileNames.name should be in quotes. As #Wolfie mentioned, you can concatenate the filenames into a cell array using {fileNames.name}
filenames_array = {fileNames.name}
Then you can iterate over filenames_array using for or cellfun

Saving figure without providing filename [duplicate]

this question about matlab:
i'm running a loop and each iteration a new set of data is produced, and I want it to be saved in a new file each time. I also overwrite old files by changing the name. Looks like this:
name_each_iter = strrep(some_source,'.string.mat','string_new.(j).mat')
and what I#m struggling here is the iteration so that I obtain files:
...string_new.1.mat
...string_new.2.mat
etc.
I was trying with various combination of () [] {} as well as 'string_new.'j'.mat' (which gave syntax error)
How can it be done?
Strings are just vectors of characters. So if you want to iteratively create filenames here's an example of how you would do it:
for j = 1:10,
filename = ['string_new.' num2str(j) '.mat'];
disp(filename)
end
The above code will create the following output:
string_new.1.mat
string_new.2.mat
string_new.3.mat
string_new.4.mat
string_new.5.mat
string_new.6.mat
string_new.7.mat
string_new.8.mat
string_new.9.mat
string_new.10.mat
You could also generate all file names in advance using NUM2STR:
>> filenames = cellstr(num2str((1:10)','string_new.%02d.mat'))
filenames =
'string_new.01.mat'
'string_new.02.mat'
'string_new.03.mat'
'string_new.04.mat'
'string_new.05.mat'
'string_new.06.mat'
'string_new.07.mat'
'string_new.08.mat'
'string_new.09.mat'
'string_new.10.mat'
Now access the cell array contents as filenames{i} in each iteration
sprintf is very useful for this:
for ii=5:12
filename = sprintf('data_%02d.mat',ii)
end
this assigns the following strings to filename:
data_05.mat
data_06.mat
data_07.mat
data_08.mat
data_09.mat
data_10.mat
data_11.mat
data_12.mat
notice the zero padding. sprintf in general is useful if you want parameterized formatted strings.
For creating a name based of an already existing file, you can use regexp to detect the '_new.(number).mat' and change the string depending on what regexp finds:
original_filename = 'data.string.mat';
im = regexp(original_filename,'_new.\d+.mat')
if isempty(im) % original file, no _new.(j) detected
newname = [original_filename(1:end-4) '_new.1.mat'];
else
num = str2double(original_filename(im(end)+5:end-4));
newname = sprintf('%s_new.%d.mat',original_filename(1:im(end)-1),num+1);
end
This does exactly that, and produces:
data.string_new.1.mat
data.string_new.2.mat
data.string_new.3.mat
...
data.string_new.9.mat
data.string_new.10.mat
data.string_new.11.mat
when iterating the above function, starting with 'data.string.mat'

Create a list and append file names to this list

I am trying to append filenames in a directory to a list for later processing. The code below does not work.
files = dir( fullfile(home,'*.csv') );
files = {files.name}'; %'# file names
symbolsList = [];
filedata = cell(numel(files),1); %# store file contents
for i=1:numel(files)
[pathstr,name,ext] = fileparts(files{i});
symbolsList(end + 1) = name; % THIS GIVES ERROR
end
In your code, symbolsList will be interpreted as an array of characters. The statement where the error is appearing is interpreted as appending a single character to symbolsList. You are probably getting a subscript alignment mismatch because a name will most likely have more than one character, yet you are trying to fit many characters into a single spot in that array of characters. That's probably not what you want.
You want each "space" to have a name. Because each name will most likely not have the same amount of characters, you should probably use a cell array instead:
files = dir( fullfile(home,'*.csv') );
files = {files.name}'; %'# file names
symbolsList = cell(numel(files),1); %// Change
filedata = cell(numel(files),1); %# store file contents
for i=1:numel(files)
[pathstr,name,ext] = fileparts(files{i});
symbolsList{i} = name; %// Change
end
Take note that I've pre-allocated the cell array and for each file you want to look at, I've indexed into the right cell and placed the name there. This is preferred over concatenation primarily due to efficiency. To access the ith name, simply do:
name_to_choose = symbolsList{i};
Minor Note
filedata in your code isn't being used anywhere at all. Are you sure you put all of your code up?

Matlab: finding/writing data from mutliple files by column header text

I have an array which I read into Matlab with importdata. It has 5 header lines
file = 'aoao.csv';
s = importdata(file,',', 5);
Matlab automatically treats the last line as the column header. I can then call up the column number that I want with
s.data(:,n); %n is desired column number
I want to be able to load up many similar files at once, and then call up the columns in the different files which have the same column header name (which are not necessarily the same column number). I want to be able to write and export all of these columns together into a new matrix, preferably with each column labelled with its file name,
what should I do?
samp = 'len-c.mp3'; %# define desired sample/column header name
file = dir('*.csv');
have the directory ready in main screen current folder. This creates a detailed description of file,
for i=1:length(file)
set(i) = importdata(file(i).name,',', 5);
end
this imports the data from each of the files (comma delimited, 5 header lines) and transports it to a cell array called 'set'
for k = 1:14;
for i=1:length(set(k).colheaders)
TF = strcmp(set(k).colheaders(i),samp); %compares strings for match
if TF == 1; %if match is true
group(:,k) = set(k).data(:,i); %save matching column# to 'group'
end
end
end
this retrieves the data from the named colheader within each file