Reputation: 33
I've been trying to use this tutorial to find moments of this pic. However I keep getting assertion failed error in line
mu[i] = moments(contours, false);
What am I doing wrong here?
#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);
}
Upvotes: 1
Views: 294
Reputation: 41765
The input of moments
should be a std::vector<cv::Point>
, not std::vector<std::vector<cv::Point>>
. You just forgot to pick the i-th contour:
mu[i] = moments(contours[i], false);
// ^^^
Upvotes: 1