opencv读取文件夹下的所有文件的文件名

opencv中有一个工具类Directory:它可以遍历对应文件夹下的所有文件,帮助读取文件夹下的所有文件名;

【注意是opencv2.0版本才有这个函数,opencv3.0中没这个函数了。。。】

 

Directory工具类中包含三个函数接口,分别是:
static std::vector< std::string > GetListFiles (const std::string &path, const std::string &exten="*", bool addPath=true)
static std::vector< std::string > GetListFilesR (const std::string &path, const std::string &exten="*", bool addPath=true)
static std::vector< std::string > GetListFolders (const std::string &path, const std::string &exten="*", bool addPath=true)
这三个函数都是static,函数只获取指定目录下的文件, 不理会目录。
(1) GetListFiles:遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹;
(2) GetListFolders:遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件;
(3) GetListFilesR:遍历指定文件夹下的所有文件,包括指定文件夹内的文件;这个R代表的recursive的意思,就是碰到文件夹还是往里钻。
path:string, 用于指定根目录
exten: string,这个是个正则表达式,匹配的返回,否则不返回。
addPath: bool,如果为true,返回的文件名会带path,如果为false,返回的仅是文件名;
 

简单示例:【读取某文件夹下的所有文件夹名,遍历每个文件夹中的图像;保存在指定路径下,按照对应文件夹保存】

    std::string savepath = "xxx/data/out/";
    std::string path0 = "xxx/data/in/";//注意最后的反斜杠
    std::string exten0 = "*";
    bool addPath0 = false;
    cv::Directory dir;
    std::vector<cv::String> foldernames = dir.GetListFolders(path0, exten0, addPath0);
    for (int fi = 0; fi < foldernames.size(); fi++)
    {
        std::string foldername = path0 + foldernames[fi] + "/image/";
        std::cout<<"\n\nProcessing Folder : "<< foldernames[fi] <<std::endl;
        std::string path1 = foldername;
        std::string exten1 = "*.png";
        bool addPath1 = false;
        vector<string> filenames = dir.GetListFiles(path1, exten1, addPath1);
        for (int i = 0; i < filenames.size(); i++)
        {
            cv::Mat test = imread(foldername + filenames[i], cv::IMREAD_GRAYSCALE);//以灰度图格式读入

            //sprintf(path, "%s%s", foldername.c_str(),filenames[i].c_str());

            //cv::Mat test = imread(path, cv::IMREAD_GRAYSCALE);


            cv::imshow("test ", test );
            cv::waitKey(1);

            std::string savepathout = savepath + foldernames[fi];//保存
            _mkdir(savepathout.c_str()); 
            cv::imwrite(savepathout + "/" + filenames[i], test);
        }
    }

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值