【发布时间】:2014-08-26 14:57:14
【问题描述】:
我编写了以下代码,使用 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”。对此感到抱歉。我已经更新了代码
【问题讨论】:
-
您从未在此代码中将
imgName设置为任何内容。结果是一个无效的文件名 (none),这会导致抛出cv::Exception,而不是由您的代码处理,因此进程终止。