OpenCV C++ 遍历文件夹下所有文件

 

如题。

一、获取完整路径

#include 
#include 

int main(int argc, char* argv[]) {

    std::string folder_path = "D:\\database\\test\\*.*"; //path of folder, you can replace "*.*" by "*.jpg" or "*.png"
    std::vector file_names;  
    cv::glob(folder_path, file_names);   //get file names

    cv::Mat img;   //try show it when file is a picture

    for (int i = 0; i < file_names.size(); i++) {
        std::cout << file_names[i] << std::endl;
        img = cv::imread(file_names[i]);
        if (!img.data) {
            continue;        
        }
        //do some work with the img you readed
        cv::imshow("img", img);
        cv::waitKey(300);
    }
    std::getchar();  //check your output on terminal
}

终端输出:

OpenCV C++ 遍历文件夹下所有文件_第1张图片

 

二、 获取文件名称

#include 
#include 

int main(int argc, char* argv[]) {

    std::string folder_path = "D:\\database\\test\\*.*"; //path of folder, you can replace "*.*" by "*.jpg" or "*.png"
    std::vector file_names;  
    cv::glob(folder_path, file_names);   //get file names

    cv::Mat img;   //try show it when file is a picture

    for (int i = 0; i < file_names.size(); i++) {

        int pos = file_names[i].find_last_of("\\");
        std::string img_name(file_names[i].substr(pos + 1));
        std::cout << img_name << std::endl;

        img = cv::imread(file_names[i]);
        if (!img.data) {
            continue;        
        }
        //do some work with the img you readed
        cv::imshow("img", img);
        cv::waitKey(300);
    }
    std::getchar();  //check your output on terminal
}

 

你可能感兴趣的:(OpenCV)