Arl*_*ong 3 c++ inheritance opencv exception
我是C++和opencv的新手.我写了一个简单的程序,你可以在下面找到,但是当我运行它时,我总是得到一个findContours(img, ctr, CV_RETR_LIST, CV_CHAIN_APPROX_NONE)由类型断言引发的异常抛出失败
OpenCV错误:断言失败(mtype == type0 ||(CV_MAT_CN(mtype)== CV_MAT_CN(type0)&&((1 << type0)&fixedDepthMask)!= 0))在create,file C:\ opencv\modu les\core\src\matrix.cpp,第1466行.
我需要一个代表单个轮廓的类并集成轮廓分析方法.我知道这CONTOUR是一个不同类型的方面,vector<Point>但因为它延伸后者,不CONTOUR应该也是一个vector<Point>类型(并以同样的方式vector<CONTOUR>也是一个vector< vector<Point> >)?我错了吗?
请注意,如果您声明CONTOUR为派生自的类vector<vector<Point>>并Ctr在下面的代码中声明作为CONTOUR对象代替vector<CONTOUR>一切正常工作.
提前谢谢了.
这是我的代码
#include "opencv2/opencv.hpp"
#include <vector>
using namespace cv;
using namespace std;
class CONTOUR : public vector<Point>
{
public:
CONTOUR() : vector<Point>(){ };
CONTOUR(const CONTOUR& orig) : vector<Point> (orig){ };
virtual ~CONTOUR(){ };
CONTOUR& operator=(const CONTOUR& rhs)
{
vector<Point> :: operator = (rhs);
return *this;
}
CONTOUR& operator=(const vector<Point>& rhs)
{
vector<Point> :: operator = (rhs);
return *this;
}
};
/** @function main */
int main(int argc, char** argv)
{
VideoCapture Camera;
if(Camera.open(0))
{
Mat img;
namedWindow("VIDEO", CV_WINDOW_AUTOSIZE);
for(;;)
{
Camera >> img;
if(!img.empty())
{
CONTOUR ctr;
RNG n(12345);
GaussianBlur(img, img, Size(5,5), 1.0, 1.0);
cvtColor(img, img, CV_BGR2GRAY);
Canny(img, img, 20, 80, 3);
findContours(img, ctr, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
Mat shape = Mat::zeros( img.size(), CV_8UC3 );
for( unsigned int i = 0; i< ctr.size(); i++ )
{
Scalar color(n.uniform(0,255), n.uniform(0,255), n.uniform(0,255));
drawContours(shape, ctr, i, color, 1, 8);
}
imshow("VIDEO", shape);
if(waitKey(30) >= 0)
{
break;
}
}
}
}
else
{
cout << "Camera not opened" << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
首先,请允许我这样说:尝试以多态方式使用标准库容器是一个坏 主意.不要这样做.在你的情况下甚至没有必要.
解决问题的方法很简单:省去class CONTOUR并通过vector<vector<cv::Point>>.这是因为cv::findContours()要求你传递一个或同等的cv::Mat.这是因为它使用代理类型作为参数,只能从这些类型构造,因此断言失败.如果要为轮廓定义速记,请使用typedef std::vector<cv::Point> Contour而不是#define CONTOUR.这为您提供了类型安全的好处.
此外,vector<CONTOUR>与... 不是同一类型vector<vector<Point>>.即使CONTOUR继承自vector<cv::Point>,它们也是不同的类型.因此,它们的载体也是不同的类型.这个答案也可能有助于理解这个问题.
另外,我注意到在你的代码中,CONTOUR派生自vector<cv::Point>.这个断言说明你需要一个向量向量:vector<vector<cv::Point>>.
| 归档时间: |
|
| 查看次数: |
4282 次 |
| 最近记录: |