C++:OpenCV批量读取文件夹下的文件

本文介绍了如何使用OpenCV在2.X和3.X版本中批量读取文件夹下的图片文件。在2.X版本中,可以利用contrib模块的Directory类的GetListFiles、GetListFolders和GetListFilesR方法。而在3.X版本中,由于contrib模块不再默认包含,需使用内置的glob函数进行文件遍历。提供的示例代码详细展示了这两种方法的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

OpenCV批量读取文件夹下的文件

批量处理图片时,可以使用OpenCV遍历文件夹下的文件来实现,OpenCV在2.X和3.X版本有较大的改动,所以有些功能并不通用。以下是在OpenCV2.X和3.X中较为简单的遍历方法。

在OpenCV 2.X的版本中包含了contrib模块,里面封装了一个Directory类,用该类就可以实现对于目录的遍历操作,在该内部包含了三个成员函数:
1)GetListFiles:遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹;
2)GetListFolders:遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件;
3)GetListFilesR:遍历指定文件夹下的所有文件,包括指定文件夹内的文件夹。

使用该方法遍历文件夹下的文件时比较简单:

#include <contrib.hpp>

cv::Directory dir;  

//case1:
std::string path1 = "E:\\src_imgs\\";  
std::string exten1 = "*.jpg"; 
bool addPath1 = false;//true;  
  
std::vector<std::string> filenames = dir.GetListFiles(path1, exten1, addPath1);  
  
std::cout<< "file names: "<< std::endl;  
for (auto file : filenames)  
    std::cout<< file << std::endl;  

//case2:
std::string path2 = "E:\\src_imgs\\";  
std::string exten2 = "*"; 
bool addPath2 = true;//false  
  
std::vector<std::string> foldernames = dir.GetListFolders(path2, exten2, addPath2);  
  
std::cout << "folder names: "<< std::endl;  
for (auto folder : foldernames)  
    std::cout << folder << std::endl;  

//case3
std::string path3 = "E:\\imgs\\";  
std::string exten3 = "*";  
bool addPath3 = true;//false  
  
std::vector<std::string> allfilenames = dir.GetListFilesR(path3, exten3, addPath3);  
  
std::cout <<"all file names: "<< std::endl;  
for (auto file: allfilenames)  
    std::cout<< file << endl;  

.

在版本转换到OpenCV3.X的时候,其内部已经不再默认包含contrib模块了,需要自己编译进去,所以这里使用的函数是自带的glob函数:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
 
using namespace cv;
using namespace std;

int main()
{
	string pattern_tif = "D:\\Photo\\*.tif";//要遍历文件的路径及文件类型
	vector<cv::String> image_files;
	glob(pattern_tif, image_files,false);//三个参数分别为要遍历的文件夹地址;结果的存储引用;是否递归查找,默认为false
	if (image_files.size() == 0)
	{
		cout << "No image files[jpg]" << endl;
		return 0;
	}
 	else
	{
		for (int i = 0; i< image_files.size(); i++)//image_file.size()代表文件中总共的图片个数
		{
			Mat image = imread(image_files.at(i));
			imshow("1", image);
			waitKey(60);
		}
	}
}

在使用时需要注意所使用的的OpenCV是哪个版本的,2.X和3.X的区别还是比较大的。以上是两种比较简单批量处理文件夹下问价的方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GISerQ.

你的鼓励将是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值