I have 200 JPEG images numbered from 1200 to 1399. How do I change their names from 1200.jpg-1400.jpg to 1.jpg-200.jpg, while keeping the original order of the image names?
This is a problem which can be tackled more efficiently in bash or other shell scripting languages. Probably, it can even be solved just via a single shell find.
Anyway, matlab can also do the job.
Consider this.
list = dir('./stack*.png'); % # assuming the file names are like stack1200.jpg
offset = -1200; # % numbering offset amount
for idx = 1:length(list) % # we go through every file name
name = list(idx).name;
number = sscanf(name,'stack%f.png',1); % # we extract the number
movefile(name,['stack' num2str(number + offset) '.png' ]); % # we rename the file.
end
I have find this solution which is quiet straightforward.
Pathfold= ('Path\to\images\');
dirData = dir('path\to\images\*.jpg');
fileNames = {dirData.name};
for i = 1:size(fileNames)
newName = sprintf('%d.jpg',i);
movefile(fileNames{i},[Pathfold , newName]) %# Rename the file
end
Related
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
I want to read multiple files from a folder, the only problem in my code down is that
instead of having the full image path:
'checkboard/Gaussian_Noised/image_01.jpg'
I have the path without the zero in the last two digits
EDIT: There is space instead of zero on the first 9 Image paths.
'checkboard/Gaussian_Noised/image_ 1.jpg'
how can I fix this please
%-------------------------------------------------------
clc
clear all
close all
%------------------------------------------------------
path = 'checkboard/Gaussian_Noised/';
% Define images to process
imageFileNames = cell(1,36);
for n = 1:36
imageFileNames{n} = strcat(path,sprintf('image_%2d.jpg',n))
end
%------------------------------------------------------
In this case, it is better to use the float-format-specifier to pad zeros:
num2str(1,'%02.f')
'01'
num2str(1,'%02.d')
'1'
num2str(1,'%2.d')
'1'
num2str(1,'%d')
'1'
So in your case:
sprintf('image_%02.f.jpg',n)
general advice
As a general advice, you may want just to check the folder for all files of a certain pattern
path2dir = pwd; % path to working directory
pattern = 'image_*.jpg'
Lst = dir(fullfile(path2dir ,pattern));
for i = 1:length(Lst)
path2file = fullfile(Lst(i).folder,Lst(i).name);
% load the file and do something with it
end
I have a folder containing a series of data with file names like this:
abc1
abc2
abc3
bca1
bca2
bca3
bca4
bca5
cba1
... etc
My goal is to load all the relevant files for each file name, so all the "abc" files, and plot them in one graph. Then move on to the next file name, and do the same, and so forth. Is there a way to do this?
This is what I currently have to load and run through all the files, grab the data in them and get their name (without the .mat extension) to be able to save the graph with the same filename.
dirName = 'C:\DataDirectory';
files = dir( fullfile(dirName,'*.mat') );
files = {files.name}';
data = cell(numel(files),1);
for i=1:numel(files)
fname = fullfile(dirName,files{i});
disp(fname);
files{i} = files{i}(1:length(files{i})-4);
disp(files{i});
[Rest of script]
end
You already found out about the cool features of dir, and have a cell array files, which contains all file names, e.g.
files =
'37abc1.mat'
'37abc2.mat'
'50bca1.mat'
'50bca2.mat'
'1cba1.mat'
'1cba2.mat'
The main task now is to find all prefixes, 37abc, 50bca, 1cba, ... which are present in files. This can be done using a regular expression (regexp). The Regexp Pattern can look like this:
'([\d]*[\D]*)[\d]*.mat'
i.e. take any number of numbers ([\d]*), then any number of non-numeric characters ([\D]*) and keep those (by putting that in brackets). Next, there will be any number of numeric characters ([\d]*), followed by the text .mat.
We call the regexp function with that pattern:
pre = regexp(files,'([\d]*[\D]*)[\d]*.mat','tokens');
resulting in a cell array (one cell for each entry in files), where each cell contains another cell array with the prefix of that file. To convert this to a simple not-nested cell array, we call
pre = [pre{:}];
pre = [pre{:}];
resulting in
pre =
'37abc' '37abc' '50bca' '50bca' '1cba' '1cba'
To remove duplicate entries, we use the unique function:
pre = unique(pre);
pre =
'37abc' '50bca' '1cba'
which leaves us with all prefixes, that are present. Now you can loop through each of these prefixes and apply your stuff. Everything put together is:
% Find all files
dirName = 'C:\DataDirectory';
files = dir( fullfile(dirName,'*.mat') );
files = {files.name}';
% Find unique prefixes
pre = regexp(files,'([\d]*[\D]*)[\d]*.mat','tokens');
pre = [pre{:}]; pre = [pre{:}];
pre = unique(pre);
% Loop through prefixes
for ii=1:numel(pre)
% Get files with this prefix
curFiles = dir(fullfile(dirName,[pre{ii},'*.mat']));
curFiles = {curFiles.name}';
% Loop through all files with this prefix
for jj=1:numel(curFiles)
% Here the magic happens
end
end
Sorry, I misunderstood your question, I found this solution:
file = dir('*.mat')
matching = regexp({file.name}, '^[a-zA-Z_]+[0-9]+\.mat$', 'match', 'once'); %// Match once on file name, must be a series of A-Z a-z chars followed by numbers.
matching = matching(~cellfun('isempty', matching));
str = unique(regexp(matching, '^[a-zA-Z_]*', 'match', 'once'));
str = str(~cellfun('isempty', str));
group = cell(size(str));
for is = 1:length(str)
ismatch = strncmp(str{is}, matching, length(str{is}));
group{is} = matching(ismatch);
end
Answer came from this source: Matlab Central
First time here so please be gentle
So the basic idea is i have folders with just txt files that has about 20000 points each. I only want specific intervals from each of them.
I have a made a single file with the ranges for that looks like this
. 2715 2955
1132 1372
each row representing the range i want in one file
I want to batch load all the files and export the just the ranges of each. Ive lost too much sleep over this please help
dirName = '*'; %# folder path
files = dir( fullfile(dirName,'*.txt') ); %# list all *.xyz files
files = {files.name}' ; %'# file names
data = cell(numel(files),1) ; %# store file contents
for u=1:numel(files)
A=files{u} ; %# full path to file
files{u};
STR1 = A
B=load(STR1);
end
This is all i have come up with in 2 days. im new to matlab
Thanks
A very good help is the matlab help of fscanf, http://www.mathworks.co.uk/help/matlab/ref/fscanf.html. Also, in your load you don't have the path. Replace the last two lines in your for loop with:
STR1 = [dirName A]
fileID = fopen(STR1,'r');
formatSpec = '%f';
B = fscanf(fileID,formatSpec)
Or try:
delim = ' ';
nrhdr = 0;
STR1 = [dirName A]
A = importdata(STR1, delim, nrhdr);
A.data will be your data, I'm assuming no header lines.
What is the best way to figure out the size of a file using MATLAB? The first thought that comes to mind is size(fread(fid)).
Please see the dir function as stated above.
Please note that the dir function works on files and not on directories only.
>> s = dir('c:\try.c')
s =
name: 'try.c'
date: '01-Feb-2008 10:45:43'
bytes: 20
isdir: 0
datenum: 7.3344e+005
You can use the DIR function to get directory information, which includes the sizes of the files in that directory. For example:
dirInfo = dir(dirName); %# Where dirName is the directory name where the
%# file is located
index = strcmp({dirInfo.name},fileName); %# Where fileName is the name of
%# the file.
fileSize = dirInfo(index).bytes; %# The size of the file, in bytes
Or, since you are looking for only one file, you can do what Elazar said and just pass an absolute or relative path to your file to DIR:
fileInfo = dir('I:\kpe\matlab\temp.m');
fileSize = fileInfo.bytes;
Use the fact that MatLab has access to Java Objects:
myFile = java.io.File('filename_here')
flen = length(myFile)
If you don't want to hardcode in your directory, you can use the built in pwd tool to find the current directory and then add your file name to it. See example below:
FileInfo = dir([pwd,'\tempfile.dat'])
FileSize = FileInfo.bytes
The question seems to indicate that fopen/fread/.. is used. In this case, why not seeking to the end of the file and reading the position?
Example:
function file_length = get_file_length(fid)
% extracts file length in bytes from a file opened by fopen
% fid is file handle returned from fopen
% store current seek
current_seek = ftell(fid);
% move to end
fseek(fid, 0, 1);
% read end position
file_length = ftell(fid);
% move to previous position
fseek(fid, current_seek, -1);
end
Matlab could have provided a shortcut..
More on ftell can be found here.
This code works for any file and directory (no need for absolute path) :
dirInfo=dir(pwd);
index = strcmp({dirInfo.name},[filename, '.ext']); % change the ext to proper extension
fileSize = dirInfo(index).bytes
Easy way to find size of file is:
enter these cammands
K=imfinfo('filename.formate');
size_of_file=K.FileSize
and get size of file.