创建文件 /home/m/OpenCV/modules/core/src/matrix_wrap.cpp,第 1461 行中的空指针(为缺少的输出数组调用了 create())

Null pointer (create() called for the missing output array) in create, file /home/m/OpenCV/modules/core/src/matrix_wrap.cpp, line 1461

我正在尝试 运行 O'reilly 书中 Drawing labeled connected components 的示例,但我在 运行 时收到以下错误消息(我构建源代码没有问题) :

#include <opencv2/opencv.hpp>
#include <algorithm>
#include <iostream>
using namespace std;
//using namespace cv;

int main(int argc, char* argv[])
{
    cv::Mat img, img_edge, labels, img_color, stats;
// load image or show help if no image was provided
    if( argc != 2|| (img = cv::imread( argv[1], 0)).empty())
    {
        cout << "\nExample 8_3 Drawing Connected componnents\n" << "Call is:\n" <<argv[0] <<" image\n\n";
        return -1;
    }
    cv::threshold(img, img_edge, 128, 255, cv::THRESH_BINARY);
    cv::imshow("Image after threshold", img_edge);
    int i, nccomps = cv::connectedComponentsWithStats (
                         img_edge, labels,
                         stats, cv::noArray()
                     );
    cout << "Total Connected Components Detected: " << nccomps << endl;
    vector<cv::Vec3b> colors(nccomps+1);
    colors[0] = cv::Vec3b(0,0,0); // background pixels remain black.
    for( i = 1; i <= nccomps; i++ )
    {
        colors[i] = cv::Vec3b(rand()%256, rand()%256, rand()%256);
        if( stats.at<int>(i-1, cv::CC_STAT_AREA) < 100 )
            colors[i] = cv::Vec3b(0,0,0); // small regions are painted with black too.
    }
    img_color = cv::Mat::zeros(img.size(), CV_8UC3);
    for( int y = 0; y < img_color.rows; y++ )
        for( int x = 0; x < img_color.cols; x++ )
        {
            int label = labels.at<int>(y, x);
            CV_Assert(0 <= label && label <= nccomps);
            img_color.at<cv::Vec3b>(y, x) = colors[label];
        }
    cv::imshow("Labeled map", img_color);
    cv::waitKey();
    return 0;
}

OpenCV(3.4.1) Error: Null pointer (create() called for the missing output array) in create, file /home/m/OpenCV/modules/core/src/matrix_wrap.cpp, line 1461 terminate called after throwing an instance of 'cv::Exception' what(): OpenCV(3.4.1) /home/m/OpenCV/modules/core/src/matrix_wrap.cpp:1461: error: (-27) create() called for the missing output array in function create

这是什么问题,我该如何解决?

使用调试器显示在调用 connectedComponentsWithStats() 期间出现此异常。错误的描述将此推断为有一些不应该那样的空/空。

OpenCV 的 current docs 显示第四个参数质心应该是 CV_64F 具有 2 列和 "centroids" 行数的矩阵。这个矩阵估计是函数自己初始化的,只要存在就可以了

因此,您只需创建此矩阵并按照函数的预期提供它:

cv::Mat centroids;
int i, nccomps = cv::connectedComponentsWithStats (img_edge, labels, stats, centroids);

您的问题在于使用 OpenCV 3.4.1(最新版),与您正在使用的书相比,它的语法发生了变化;这是任何开源库的常见问题。我建议您保留当前的 ​​OpenCV 文档,以确保书中的代码仍然有效,或者降级到旧版本。