MATLAB图像批量剪切
Github: loper-eswai/MagicLab
问题描述
源文件夹下有若干子文件夹,包含不同类别的图片文件。现要求将每个图片剪切成相同大小,保存在目标文件夹。
解决方案
参数设置:
- src_dir: 源文件夹 [字符串]
- dst_dir: 目标文件夹 [字符串]
- format: 图片文件格式 [字符串]
- spacing: 剪切间隔,即小图片的大小为spacing × spacing
function ImageCrop(src_dir,dst_dir,format,spacing)
subfolders=dir(src_dir);
for ii=1:length(subfolders)
subname=subfolders(ii).name;
% ignore current dir and father dir
if ~strcmp(subname,'.')&&~strcmp(subname,'..')
frames=dir(fullfile(src_dir,subname,['*.',format]));
imgnum=length(frames);
dstpath=fullfile(dst_dir,subname);
if ~isdir(dstpath)
mkdir(dstpath);
end
for jj=1:imgnum
imgpath=fullfile(src_dir,subname,frames(jj).name);
I=imread(imgpath);
row=floor(size(I,1)/spacing);
col=floor(size(I,2)/spacing);
% Start Croping
for rr=1:row
for cc=1:col
rect=[(cc-1)*spacing+1,(rr-1)*spacing+1,spacing-1,spacing-1];
newI=imcrop(I,rect);
newname=[frames(jj).name,'_',num2str((rr-1)*col+cc),['.',format]];
newpath=fullfile(dstpath,newname);
imwrite(newI,newpath);
end
end
end
end % end of if
end
end
p.s. 如果和您的需求有差异请自行修改哦~