OpenCV Assertion在计算时刻时失败

时间:2016-05-26 14:10:21

标签: c++ opencv

我一直在尝试使用this教程来查找此pic的时刻。但是我继续在行

中获得断言失败错误
mu[i] = moments(contours, false);

我在这里做错了什么?

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;

int main(int, char *[]) {
    cv::Mat roi = cv::imread("ROI.jpg");
    cv::Mat kontury = roi;
    cv::cvtColor(roi, kontury, CV_RGB2GRAY);
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    findContours(kontury, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); 

    /// Get the moments
    vector<Moments> mu(contours.size());
    for (int i = 0; i < contours.size(); i++)
    {
        mu[i] = moments(contours, false);
    }

    ///  Get the mass centers:
    vector<Point2f> mc(contours.size());
    for (int i = 0; i < contours.size(); i++)
    {
        mc[i] = Point2f(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
    }

    /// Calculate the area with the moments 00 and compare with the result of the OpenCV function
    Mat drawing = Mat::zeros(roi.size(), CV_8UC3);

    printf("\t Info: Area and Contour Length \n");
    for (int i = 0; i< contours.size(); i++)
    {
        printf(" * Contour[%d] - Area (M_00) = %.2f - Area OpenCV: %.2f - Length: %.2f \n", i, mu[i].m00, contourArea(contours[i]), arcLength(contours[i], true));
        Scalar color = Scalar(rand() % 256, rand() % 256, rand() % 256);
        drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
        circle(drawing, mc[i], 4, color, -1, 8, 0);
    }

    cv::waitKey(-1);
}

1 个答案:

答案 0 :(得分:1)

moments的输入应为std::vector<cv::Point>,而不是std::vector<std::vector<cv::Point>>。你只是忘了选择第i个轮廓:

mu[i] = moments(contours[i], false);
//                      ^^^