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

Loading an image from a folder using OpenCV 3.0 in Windows

本文关键字:文件夹 加载 图像 OpenCV Windows      更新时间:2023-10-16

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

首先,我没有文件 dirent.h,所以我下载了它,以便获取 DIR* 和"dirent*"结构来访问文件。一切似乎都很好,但现在当我上线时

字符串文件名 = 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 directoryn");
                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());

提前谢谢。

对于更简单的解决方案,只需使用 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]);
   ...
}