使用OpenCV读取文件夹中的有序序列的图像 [英] Reading an ordered sequence of images in a folder using OpenCV
问题描述
我有以下示例代码,其中显示我的网络摄像头。
I have this following example code, where I'm displaying my webcam.
但是如何在一个文件夹中显示一系列图片:
But how can I display a sequence of pictures in a folder like:
0.jpg
1.jpg
2.jpg
... and so on
使用 imread
?
我想使用该文件夹作为输入,而不是我的网络摄像头。
I would like to use that folder as input instead of my webcam.
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
int main()
{
cv::VideoCapture capture(0);
cv::Mat myImage;
while(1)
{
capture>> myImage;
cv::imshow( "HEYO", myImage);
int c = cv::waitKey(1);
}
return 0;
}
推荐答案
code> VideoCapture 和 filename :
1) You can use VideoCapture
with a filename:
filename - 打开的视频文件(例如video.avi)或图像序列的名称strong> img_%02d.jpg ,会读取像img_00.jpg,img_01.jpg,img_02.jpg,...)的样本
filename – name of the opened video file (eg. video.avi) or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, ...)
2)或者只是更改要根据计数器加载的图像的名称。
2) Or simply change the name of the image to load according to a counter.
#include <opencv2/opencv.hpp>
#include <string>
#include <iomanip>
#include <sstream>
int main()
{
std::string folder = "your_folder_with_images";
std::string suffix = ".jpg";
int counter = 0;
cv::Mat myImage;
while (1)
{
std::stringstream ss;
ss << std::setw(4) << std::setfill('0') << counter; // 0000, 0001, 0002, etc...
std::string number = ss.str();
std::string name = folder + number + suffix;
myImage = cv::imread(name);
cv::imshow("HEYO", myImage);
int c = cv::waitKey(1);
counter++;
}
return 0;
}
3)也可以使用函数 glob 来存储与向量中给定模式匹配的所有文件名,以及然后扫描向量。这也将用于非连续数字。
3) Or you can use the function glob to store all the filenames matching a given pattern in a vector, and then scan the vector. This will work also for non-consecutive numbers.
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
String folder = "your_folder_with_images/*.jpg";
vector<String> filenames;
glob(folder, filenames);
Mat myImage;
for (size_t i = 0; i < filenames.size(); ++i)
{
myImage = imread(filenames[i]);
imshow("HEYO", myImage);
int c = cv::waitKey(1);
}
return 0;
}
这篇关于使用OpenCV读取文件夹中的有序序列的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!