我编写了以下代码,使用 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 还是其他系统?
有关更多信息,请参阅以下链接:
OpenCV imread(filename) fails in debug mode when using release libraries
要解决此问题,也许您可以尝试使用 C 接口(interface),尤其是 cvLoadImage
。
关于c++ - 使用 imread 读取目录中的所有图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588358/