OpenCV错误:空数组指针Java

时间:2013-12-29 23:39:05

标签: java opencv nullpointerexception

我正在运行网络摄像头,试图实时检测对象并运行此代码。它在video.main(video.java:92) - CvRect sq = cvBoundingRect(ptr, 0);给出了错误,但我正在检查if(ptr != null)。我不明白为什么。

CvMemStorage storage = CvMemStorage.create();
CvSeq contours = new CvContour(null);          
noOfContors = cvFindContours(imgbin, storage, contours, Loader.sizeof(CvContour.class), CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE, new CvPoint(0,0));


 for (ptr = contours;  ptr != null; ptr = ptr.h_next()) {     
    if(ptr != null){
         CvRect sq = cvBoundingRect(ptr, 0);
         if(sq.height()*sq.width() > minAreaa && sq.height()* sq.width() < maxAreaa){
            p1.x(sq.x());
            p2.x(sq.x()+sq.width());
            p1.y(sq.y());
            p2.y(sq.y()+sq.height());
            cvRectangle(img1, p1, p2, CV_RGB(255, 0, 0), 2, 8, 0);
        } 
    }
}

在命令窗口中:

 OpenCV Error: Null pointer (NULL array pointer is passed) in unknown function, file ..\..\..\src\opencv\modules\core\src\array.cpp, line 2382
Exception in thread "main" java.lang.RuntimeException: ..\..\..\src\opencv\modules\core\src\array.cpp:2382: error: (-27) NULL array pointer is passed

    at com.googlecode.javacv.cpp.opencv_imgproc.cvBoundingRect(Native Method)
    at video.main(video.java:92)

2 个答案:

答案 0 :(得分:2)

通过在for循环中添加其他条件来解决问题,但仍然不知道它是否是一种正确的处理方式:

CvSeq contours1 = new CvContour(null);
for (ptr = contours;  ptr != null && cvFindContours(imgbin, storage, contours1, Loader.sizeof(CvContour.class), CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE, new CvPoint(0,0)) != 0; ptr = ptr.h_next()){ .....

}

答案 1 :(得分:0)

请改用以下内容:

 for (ptr = contours; ptr != null && !ptr.isNull(); ptr = ptr.h_next()) {

!ptr.isNull()修复了空指针错误。