前言
OpenCV —— Open Source Computer Vision
OpenCV是一个跨平台的计算机视觉库。是由英特尔公司发起并参与开发,以BSD许可证授权发行,可以在商业和研究领域中免费使用。可用于开发实时的图像处理、计算机视觉以及模式识别程序。
在使用C++调用OpenCV接口时,我们有时会有类似Python下的glob.glob方法获取某个文件路径下的所有文件的需求,在OpenCV中这一具体方法可以通过调用cv::glob()实现。
使用
#include <iostream>
#include <vector>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define CV_LOAD_IMAGE_COLOR 1
int main(int argc, char *argv[]) {
std::string input_img_path_parent = argv[1];// 文件夹路径,例如"/home/user/test"
std::string input_img_path;
std::vector<std::string> filePaths; // vector用于保存所有文件的路径
cv::glob(input_img_path_parent+"/*", filePaths, false);
std::vector<std::string >::iterator input_img_path_it;
cv::Mat img;
cv::Mat img_gray;
int cnt = 0;
for (input_img_path_it = filePaths.begin(); input_img_path_it != filePaths.end(); ++input_img_path_it){
cnt++;
input_img_path = *input_img_path_it; //获取实际文件路径字符串
img = cv::imread(input_img_path, CV_LOAD_IMAGE_COLOR);
cv::cvtColor(img, img_gray, cv::COLOR_BGR2GRAY);
cv::imwrite("img_gray-"+std::to_string(cnt)+".png", img_gray);
}
return 0;
}
参考资料
[1] OpenCV - glob()方法
[2] c++利用opencv的glob读取目录下特定格式文件路径并按文件名排序后输出到vector
[3] Easiest way to convert int to string in C++