使用c++遍历文件夹,使用opencv循环显示读取到的图像
时间: 2023-05-22 15:00:35 浏览: 213
可以使用以下代码来遍历文件夹并使用OpenCV循环显示读取到的图像:
```c
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv)
{
if (argc != 2) {
printf("Usage: %s <directory>\n", argv[0]);
return -1;
}
DIR* dir;
struct dirent* ent;
if ((dir = opendir(argv[1])) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_REG) {
char filename[1024];
sprintf(filename, "%s/%s", argv[1], ent->d_name);
Mat img = imread(filename);
if (img.empty()) {
printf("Failed to read image: %s\n", filename);
continue;
}
imshow("Image", img);
waitKey(0);
}
}
closedir(dir);
} else {
printf("Failed to open directory: %s\n", argv[1]);
return -1;
}
return 0;
}
```
这个程序会接收一个文件夹路径作为命令行参数,然后遍历该文件夹中的所有文件,如果是图像文件,则使用OpenCV读取并显示。使用`waitKey(0)`可以让程序等待用户按下任意键后再继续执行下一个图像的读取和显示。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)