MATLAB 批量 修改图像尺寸 修改文件名 移动文件
记录一下常用的 MATLAB 批处理操作。
%--->This file contains three sub batch-programes<---
% 1. resize images;
% 2. rename files;
% 3. copy files to another directory.
%---> Created environment: Matlab R2014b <---
%--->Get name of the directory appointed<---
src_dir='D:\detection\dataset1';
dst_dir='D:\detection\dataset2';
%---> Extract files as cell<---
file_info = dir(src_dir);
if src_dir(end) ~= '/'
src_dir = [src_dir,'/'];
end
file_name = struct2cell(file_info);
file_name = file_name(1,3:end)';
%===============Resize images==============%
for i=1:size(file_name,1)
image_name = [src_dir,char(file_name(i))];
img=imread(char(image_name));
h=size(img,1);
w=size(img,2);
if h>700 || w>700 % scale large images
img_resized=imresize(img,0.5,'bilinear');
else
img_resized=imresize(img,0.7,'bilinear');
end
img_save_name=strcat(dst_dir,'\',num2str(i),'.jpg');
imwrite(img_resized,img_save_name);
end
%==================Rename files in the same directory==========%
%切记把程序放在待修改文件夹的里面!!!!!!!!!!!!!!
for i=1:size(file_name,1)
image_name = [src_dir,char(file_name(i))];
file=strsplit(char(image_name),'/');
old_name=char(file(end));
file_split=strsplit(old_name,'.');
if size(file_split,2)==3
temp=file_split(1,1);
index=strfind(temp,'_');
split_start=index{1,1}+1;
prefix_name=temp{1,1}(1,splitAt:end);
new_name=char(strcat(prefix_name,'.txt'));
command = ['rename' 32 oldname 32 newname];
status = dos(command);
end
end
%============Copy files to another directory===============
%移动指定的文件。
for i=1:size(file_name,1)
image_name = [src_dir,char(file_name(i))];
file=strsplit(char(image_name),'/');
old_name=char(file(end));
file_split=strsplit(old_name,'.');
if size(file_split,2)==4
if strcmp(file_split(1,3),'gt') % 'png', 'jpg', 'txt'
%copy x.txt to GT or copy x.jpg to Images
copyfile(image_name,dst_dir);
end
end
end