MATLAB: 图像批量剪切

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. 如果和您的需求有差异请自行修改哦~

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值