opencv读取文件夹下所有文件

如题。

一、获取完整路径

#include <opencv2\opencv.hpp>
#include <string>
 
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<cv::String> 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
}

二、 获取文件名称

#include <opencv2\opencv.hpp>
#include <string>
 
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<cv::String> 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
}
发布了210 篇原创文章 · 获赞 105 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_30263737/article/details/100714264