使用VideoCapture读取目录中的图像不起作用

Reading images in directory using VideoCapture not working

本文关键字:图像 不起作用 VideoCapture 读取 使用      更新时间:2023-10-16

我正在尝试读取多个名为001.jpg、002.jpg、003.jpg及以上的图像文件,方法是在Linux上使用OpenCV,并在一段延迟后将其显示在窗口中。这是我的代码-

int main(int argc, char ** argv){
    cv::VideoCapture cam("/home/bikz05/Desktop/dataset/%03d.jpg");
    if (!cam.isOpened())
        cout << "Capture is not opened";
    cv::Mat image;
    const string Window = "Image Number";
    namedWindow(Window, CV_WINDOW_NORMAL);
    while(true) {
        cam >> image;
        if (!image.data) {
            std::cout << "Preview Ends" << std::endl;
            break;
        }
        cv::imshow(Window, image);
        waitKey(1000);
    }
    return 0;
}

在主功能的第一行中,我甚至尝试使用

cv::VideoCapture cam("/home/bikz05/Desktop/dataset/001.jpg");

我甚至试着把图像和二进制文件放在同一个文件夹里,即使这样也无济于事。

在这两种情况下,它都只显示第一个图像,然后程序退出。注意,它还没有结束。

附言:Stack Exchange和opencv.org上提供的答案并没有产生预期的结果。

您编写的代码有几个问题,但如果要从磁盘读取图像,请使用cv::imread()而不是cv::VideoCapture:

std::string filename = "/home/bikz05/Desktop/dataset/001.jpg";
const std::string Window = "Image Number";
cv::namedWindow(Window, CV_WINDOW_NORMAL);
while (true) 
{
    cv::Mat image = cv::imread(filename.c_str());
    if (!image.data) 
    {
        std::cout << "!!! File not found: " << filename << std::endl;
        break;
    }
    cv::imshow(Window, image);
    cv::waitKey(1000);
    // And before the loop ends, update filename with the next image:
    // filename = ???;
}

我还没有测试过,但我相信你已经明白了。

使用glob作为glob(folderpath, vectorOfimages),然后访问每个图像作为vectorOfimages[i]

vectorOfimages是

 vector<String>

folderpath是一个字符串。

我遇到了同样的问题,videoCapture无法解决。