我正在尝试学习C和OpenCV。我正在使用以下代码,受到 O'Reilly Learning OpenCV 的启发,但是我收到错误并且图像没有按预期显示。这段代码有问题吗?
# include "cv.h"
# include "highgui.h"
IplImage * doCanny(IplImage *in, double lowThresh, double highThresh, int aperture) {
if(1 != in->nChannels){
return 0;
}
IplImage *out = cvCreateImage(cvGetSize(in), IPL_DEPTH_8U, 1);
cvCanny(in, out, lowThresh, highThresh, aperture);
return out;
}
/* This layout works with other functions like cvPyrdown, but for some reason it doesn't work with cvCanny */
int main() {
double lowThresh = 50;
double highThresh = 150;
int aperture = 3;
IplImage *img = cvLoadImage("/tmp/lena.jpg", CV_LOAD_IMAGE_UNCHANGED);
IplImage *out = doCanny(img, lowThresh, highThresh, aperture);
cvNamedWindow("Example2-6", CV_LOAD_IMAGE_UNCHANGED);
cvShowImage("Example2-6", out);
cvWaitKey(0);
cvReleaseImage(&img);
cvReleaseImage(&out);
cvDestroyWindow("Example2-6");
return 0;
}
我在Mac OS X Yosemite上获得的输出是:
OpenCV错误:cvGetMat中的空指针(传递NULL数组指针),文件/opt/local/var/macports/build/.../opencv-2.4.11/.../array.cpp,第2382行
答案 0 :(得分:1)
您的 jpg 图像很可能是三通道图像。您将此图片作为in
传递到doCanny()
函数中。以下代码将导致doCanny()
函数返回0:
if(1 != in->nChannels){
return 0;
}
然后您不检查doCanny()
函数的返回值是否有效。因此,您将空指针传递给以下函数,这可能会导致您的空指针错误:
cvShowImage("Example2-6", out);
为了让您的代码能够处理三通道图像,您应该将in
功能中的doCanny()
图像转换为单通道图像:
IplImage * doCanny(IplImage *in, double lowThresh, double highThresh, int aperture) {
IplImage *out = cvCreateImage(cvGetSize(in), IPL_DEPTH_8U, 1);
/* Convert the three-channel input image into a single-channel image. */
IplImage* oneChannel = cvCreateImage(cvGetSize(in), IPL_DEPTH_8U, 1);
cvCvtColor(in, oneChannel, CV_BGR2GRAY);
cvCanny(oneChannel, out, lowThresh, highThresh, aperture);
return out;
}
或者,您可以将CV_LOAD_IMAGE_GRAYSCALE
作为第二个参数传递给cvLoadImage()
,直接将输入图像加载为单通道图像:
IplImage *img = cvLoadImage("/tmp/lena.jpg", CV_LOAD_IMAGE_GRAYSCALE);
无论如何,您应该始终检查函数返回的值是否有效。
答案 1 :(得分:1)
它对我有用:
#include "opencv/cv.h"
#include "opencv/highgui.h"
#include "opencv2/core/core_c.h"
using namespace cv;
IplImage * doCanny(IplImage *in, double lowThresh, double highThresh, int aperture)
{
if(1 != in->nChannels)
{ return 0; }
IplImage *out = cvCreateImage(cvGetSize(in),IPL_DEPTH_8U, 0);
cvCanny(in, out, lowThresh, highThresh, aperture);
return (out);
}
int main()
{
double lowThresh = 50;
double highThresh = 150;
int aperture = 3;
IplImage *img = cvLoadImage("/tmp/lena.jpg",0);
IplImage *out = doCanny(img, lowThresh, highThresh, aperture);
cvNamedWindow("Example2-6", 0);
cvShowImage("Example2-6", out);
cvWaitKey(0);
cvReleaseImage(&img);
cvReleaseImage(&out);
cvDestroyWindow("Example2-6");
return 0;
}
如果问题仍然存在,请访问