在Windows中使用OpenCV 3.0从文件夹加载图像

时间:2016-01-19 14:57:36

标签: c++ windows visual-studio-2010 opencv3.0

我正在使用OpenCV 3.0的Visual Studio 2010。我正在尝试从文件夹加载一些图像,但我遇到了问题。

首先我没有文件dirent.h,所以我下载它是为了获得DIR *和“dirent *”结构来访问文件。一切似乎都很好,但现在我到了这条线

  

string fileName = in_file-> d_name;

我发现我无法访问该文件的名称。

有人对此有任何想法吗?

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <opencv2/core/dirent.h>

#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif

#include <conio.h>
#include <windows.h>
#include <tchar.h> 
#include <stdio.h>
#include <strsafe.h>
#pragma comment(lib, "User32.lib")

#include <errno.h>
#include <iostream>
#include <time.h>
#include <limits.h>
#include <fstream>
#include <sys/stat.h>

#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace cv::ml;
using namespace std;

int patchWidth = 15;
int patchHeight = 15;


int main(int, char**)
{
    string imagesPath = "Images";
    string resultsPath = "Patches";

            DIR* FD;
            struct dirent* in_file;

            if (NULL == (FD = opendir (imagesPath.c_str())))
            {
                fprintf(stderr, "Error : Failed to open input directory\n");
                return 0;
            }

            while ((in_file = readdir(FD)))
            {
                    /* On linux/Unix we don't want current and parent directories
                     * If you're on Windows machine remove this two lines
                     */
              //      if (!strcmp (in_file->d_name, "."))
              //          continue;
              //      if (!strcmp (in_file->d_name, ".."))
              //          continue;

                    /* Open directory entry file for common operation */
                    /* TODO : change permissions to meet your need! */

                    string fileName = in_file->d_name;

                    string pathFile = imagesPath;
                    pathFile.append("/");
                    pathFile.append(fileName);
                    //pathFile.append(".jpg");
                    Mat img = imread(pathFile.c_str());

提前致谢。

1 个答案:

答案 0 :(得分:3)

要获得更简单的解决方案,只需使用cv::glob

String imagesPath = "Images/*.png"; // it has filters, too !

vector<String> fn;
glob(path, fn, true); // recursive, if you want
for (size_t i=0; i<fn.size(); i++)
{
   Mat img = imread(fn[i]);
   ...
}