opencv实现遍历文件夹下所有文件

前言

最近需要将视频数据集中的每个视频进行分割,分割成等长的视频片段,前提是需要首先遍历数据集文件夹中的所有视频。

实现

1.了解opencv中的Directory类;

2.实现测试代码;

系统环境

OS:win7_64;

opencv版本:2.4.10;

VS版本:VS2013

实现过程

1.了解opencv中的Directory类;

1)opencv中有实现遍历文件夹下所有文件的类Directory,包含3个成员函数:

(1)GetListFiles:遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹;

(2)GetListFolders:遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件;

(3)GetListFilesR:遍历指定文件夹下的所有文件,包括指定文件夹内的文件夹。

class CV_EXPORTS Directory
{
public:
    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 );
};

注意,其中addPath变量表示输出变量是否add到path变量;

2)若要使用Directory类,则需包含contrib.hpp头文件,此类的实现在contrib模块。

模块的具体路径:

.opencvuildincludeopencv2contrib

#include “opencv2/contrib/contrib.hpp”

2.实现测试代码;

    cv::Directory dir;

    string path1 = "E:/data/image";
    string exten1 = "*.bmp";//"*"
    bool addPath1 = false;//true;

    vector<string> filenames = dir.GetListFiles(path1, exten1, addPath1);

    cout<<"file names: "<<endl;
    for (int i = 0; i < filenames.size(); i++)
        cout<<filenames[i]<<endl;

    string path2 = "E:/data/image";
    string exten2 = "*";//"Image*";//"*"
    bool addPath2 = true;//false

    vector<string> foldernames = dir.GetListFolders(path2, exten2, addPath2);

    cout<<"folder names: "<<endl;
    for (int i = 0; i < foldernames.size(); i++)
        cout<<foldernames[i]<<endl;

    string path3 = "E:/data/image";
    string exten3 = "*";
    bool addPath3 = true;//false

    vector<string> allfilenames = dir.GetListFilesR(path3, exten3, addPath3);

    cout<<"all file names: "<<endl;
    for (int i = 0; i < allfilenames.size(); i++)
        cout<<allfilenames[i]<<endl;

问题:
实现的过程中出现warning提示,

warning C4101:“dir”:未引用的局部变量;

暂时还没有找到这个warning的解决方法;不过不影响实现;

参考

1.大牛博客

2.实例

原文地址:https://www.cnblogs.com/happyamyhope/p/7728817.html