c++ - 使用 OpenCV 读取文件夹中的有序图像序列

标签 c++ opencv

我有以下示例代码,我在其中显示我的网络摄像头。

但是我怎样才能在一个文件夹中显示一系列图片:

0.jpg 
1.jpg 
2.jpg
... and so on 

使用imread

我想使用该文件夹而不是我的网络摄像头作为输入。

#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;
}

最佳答案

1) 您可以将 VideoCapturefilename 一起使用:

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) 或者根据计数器更改要加载的图像的名称。

#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将与给定模式匹配的所有文件名存储在一个 vector 中,然后扫描该 vector 。这也适用于非连续数字。

#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;
}

关于c++ - 使用 OpenCV 读取文件夹中的有序图像序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32550620/

相关文章:

opencv - 具有不对称圆网格的正方形大小openCV

c++ - 如何使用数组查找标准差

c++ - CPP中的libxml程序

c++ - Windows 设备驱动程序不以参数 0 启动

python - 如何使用 OpenCV 去除灰度图像的七个低位

python - 在 POST 响应中发送 OpenCV 图像

c++ - OpenCV 图像从 RGB 到 HSV 的转换

python - OpenCV不在Docker内部显示图像

c++ - 使用模板参数添加数据

c++ - 无法在 Mac 终端中运行 qmake