c++ - 使用 imread 读取目录中的所有图像文件

标签 c++ opencv

我编写了以下代码,使用 imread 读取目录中的所有图像文件。但是代码不工作并给出错误。

#include<iostream>
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/core/core.hpp>
#include<dirent.h>
#include<string.h>
using namespace std;
using namespace cv;
int main(){
    string dirName = "/home/Dataset/newImage";
    DIR *dir;
    dir = opendir(dirName.c_str());
    string imgName;
    struct dirent *ent;
    if (dir != NULL) {
        while ((ent = readdir (dir)) != NULL) {
             imgName= ent->d_name;
            Mat img = imread(imgName);
            cvtColor(img,img,CV_BGR2GRAY);
        }
        closedir (dir);
    } else {
        cout<<"not present"<<endl;
    }
}

错误:

    OOpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /build/buildd/opencv-2.3.1/modules/imgproc/src/color.cpp, line 2834
terminate called after throwing an instance of 'cv::Exception'
  what():  /build/buildd/opencv-2.3.1/modules/imgproc/src/color.cpp:2834: error: (-215) scn == 3 || scn == 4 in function cvtColor

Aborted (core dumped)

我实际上忘记在前面的代码中添加行“imgName = ent->d_name”。对不起。我已经更新了代码

最佳答案

这是失败的,因为 imread 只获取文件名,而不是完整路径。看这个SO question .

    while ((ent = readdir (dir)) != NULL) {
         imgName= ent->d_name;
        Mat img = imread(imgName);
        cvtColor(img,img,CV_BGR2GRAY);
    }

应该是这样的

    while ((ent = readdir (dir)) != NULL) {
        string imgPath(dirName + ent->d_name);
        Mat img = imread(imgPath);
        cvtColor(img,img,CV_BGR2GRAY);
    }

我不熟悉 dirent,因为我更喜欢用 boost::filesystem 来做这种事情。顺便说一句,我打赌一些“printf 调试”在这里会有所帮助,以查看导致失败的“imread”的参数。

编辑:

看起来 OpenCV 的 imread 有一些已知问题,这取决于您的程序是如何构建的。您的系统是 Windows 还是其他系统?

有关更多信息,请参阅以下链接:

imread not working in Opencv

OpenCV imread(filename) fails in debug mode when using release libraries

要解决此问题,也许您可​​以尝试使用 C 接口(interface),尤其是 cvLoadImage

关于c++ - 使用 imread 读取目录中的所有图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588358/

相关文章:

c++ - 如何存储击键?

c# - 是否有与 C++ 的 std::set_difference 等效的 C#?

java - 为什么 Opencv Imgproc.minAreaRect 以不同的顺序对相同的点(构成不对称三角形)给出不同的结果?

c++ - 如何加载 txt/.pgn.camera 文件并将其存储在 c++/opencv 的矩阵中

opencv - 我正在使用拼接器类从多个图像创建全景图。如何减少计算时间?

c++附加到线程(获得焦点)

c++ - 用c/c++实现实时最佳拟合内存分配算法

opencv - cvMulTransposed和输出矩阵的尺寸?

c++ - 使用 opencv 从网络摄像机获取高分辨率图像

C++ 在另一个函数中调用函数