gpt4 book ai didi

c++ - OpenCV:findContours 函数错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:59 25 4
gpt4 key购买 nike

我正在使用 2.4.3 版的 opencv,并尝试在 canny 边缘检测之后使用“findContours”函数,如下所示:

struct Component
{
cv::Rect boundingBox;
double area;
double circularity;
}

cv::vector < Component > components;
cv::vector < cv::Vec4i > hierarchy;
cv::findContours ( cannyEdges, components, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);

然后它会像这样为行“cv::findContours”抛出错误:

OpenCV Error: Assertion failed (mtype == type0 || ( CV_MAT_CN(mtype) == CV_MAT_CN(type0) && ((1((type0) & fixedDepthMask) != 0 )) in unknown function, file ...\opencv\modeuls\core\src\matrix.cpp, line 1421

我该如何解决这个问题?

最佳答案

cv::findcontours 将每个轮廓作为点 vector 返回(参见 http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours)。

您必须自己将这些 vector 转换为您的数据结构(组件),就像我创建的这个最小示例:

#include <opencv2/opencv.hpp>
#include <iostream>
struct Component
{
cv::Rect boundingBox;
double area;
double circularity;
};
int main()
{
// Create a small image with a circle in it.
cv::Mat image(256, 256, CV_8UC3, cv::Scalar(0, 0, 0));
cv::circle(image, cv::Point(80, 110), 42, cv::Scalar(255,127, 63), -1);

// Find canny edges.
cv::Mat cannyEdges;
cv::Canny(image, cannyEdges, 80, 60);

// Show the images.
cv::imshow("img", image);
cv::imshow("cannyEdges", cannyEdges);

// Find the contours in the canny image.
cv::vector<cv::Vec4i> hierarchy;

// "Each contour is stored as a vector of points."
// http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours
typedef cv::vector<cv::vector<cv::Point> > TContours;
TContours contours;
cv::findContours(cannyEdges, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);
// cannyEdges is destroyed after calling cv::findContours

// Print number of found contours.
std::cout << "Found " << contours.size() << " contours." << std::endl;

// Convert contours to Components.
typedef cv::vector<Component> TComponents;
TComponents components;
for (TContours::const_iterator it( contours.begin() ); it != contours.end(); ++it)
{
Component c;
c.area = cv::contourArea(*it);
c.boundingBox = cv::boundingRect(*it);
c.circularity = 0.0; // Insert whatever you mean by circularity;
components.push_back(c);
}

for (TComponents::const_iterator it( components.begin() ); it != components.end(); ++it)
std::cout << it->area << std::endl; // and whatever you want.

// Wait for user input.
cv::waitKey();
}

关于c++ - OpenCV:findContours 函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13646855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com