How to read multiple images from a folder in open cv (using C)

后端 未结 2 1595
Happy的楠姐
Happy的楠姐 2021-01-17 03:17

I am new to open CV and C. How do i specify multiple images for the same kind of operation.

相关标签:
2条回答
  • 2021-01-17 03:53

    if your images are (sequentially) numbered, you could abuse a hidden feature with VideoCapture, just pass it a (format) string:

    VideoCapture cap("/my/folder/p%05d.jpg"); // would work with: "/my/folder/p00013.jpg", etc
    while( cap.isOpened() )
    {
        Mat img;
        cap.read(img);
        // process(img);
    }
    
    0 讨论(0)
  • 2021-01-17 04:17

    OpenCV doesn't provide any functionality for this. you can use a third party lib for reading the files from the file system. in case your images are sequentially numbered you can use @berak technique but if your files are not sequential then use can use boost::filesystem (heavy and my favorite) for reading the file. or dirent.h (small, single header only) library.
    Following code uses dirent.h for this job

    #include <iostream>
    #include <opencv2\opencv.hpp>
    #include "dirent.h"
    int main(int argc, char* argv[])
    {
    
        std::string inputDirectory = "D:\\inputImages";
        std::string outputDirectory = "D:\\outputImages";
        DIR *directory = opendir (inputDirectory.c_str());
        struct dirent *_dirent = NULL;
        if(directory == NULL)
        {
            printf("Cannot open Input Folder\n");
            return 1;
        }
        while((_dirent = readdir(directory)) != NULL)
        {
            std::string fileName = inputDirectory + "\\" +std::string(_dirent->d_name);
            cv::Mat rawImage = cv::imread(fileName.c_str());
            if(rawImage.data == NULL)
            {
                printf("Cannot Open Image\n");
                continue;
            }
            // Add your any image filter here
            fileName = outputDirectory + "\\" + std::string(_dirent->d_name);
            cv::imwrite(fileName.c_str(), rawImage);
        }
        closedir(directory);
    }
    
    0 讨论(0)
提交回复
热议问题