我想使用cvDrawContours绘制自己从CvSeq创建的轮廓(通常,轮廓从OpenCV的其他函数中退出)。这是我的解决方案,但它不起作用:(
IplImage* g_gray = NULL;
CvMemStorage *memStorage = cvCreateMemStorage(0);
CvSeq* seq = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvPoint)*4, memStorage);
CvPoint points[4];
points[0].x = 10;
points[0].y = 10;
points[1].x = 1;
points[1].y = 1;
points[2].x = 20;
points[2].y = 50;
points[3].x = 10;
points[3].y = 10;
cvSeqPush(seq, &points);
g_gray = cvCreateImage( cvSize(300,300), 8, 1 );
cvNamedWindow( "MyContour", CV_WINDOW_AUTOSIZE );
cvDrawContours(
g_gray,
seq,
cvScalarAll(100),
cvScalarAll(255),
0,
3);
cvShowImage( "MyContour", g_gray );
cvWaitKey(0);
cvReleaseImage( &g_gray );
cvDestroyWindow("MyContour");
return 0;
我从这篇文章中选择了从CvPoint创建自定义轮廓序列的方法 OpenCV sequences -- how to create a sequence of point pairs?
第二次尝试,我是用Cpp OpenCV做的:
vector<vector<Point2i>> contours;
Point2i P;
P.x = 0;
P.y = 0;
contours.push_back(P);
P.x = 50;
P.y = 10;
contours.push_back(P);
P.x = 20;
P.y = 100;
contours.push_back(P);
Mat img = imread(file, 1);
drawContours(img, contours, -1, CV_RGB(0,0,255), 5, 8);
也许我错误地使用了数据。编译器警告错误&amp;不允许push_back指向这样的向量。为什么?
错误是这样的: 错误2错误C2664:'std :: vector&lt; _Ty&gt; :: push_back':无法将参数1从'cv :: Point2i'转换为'const std :: vector&lt; _Ty&gt; &安培;'
答案 0 :(得分:1)
我终于完成了它。
Mat g_gray_cpp = imread(file, 0);
vector<vector<Point2i>> contours;
vector<Point2i> pvect;
Point2i P(0,0);
pvect.push_back(P);
P.x = 50;
P.y = 10;
pvect.push_back(P);
P.x = 20;
P.y = 100;
pvect.push_back(P);
contours.push_back(pvect);
Mat img = imread(file, 1);
drawContours(img, contours, -1, CV_RGB(0,0,255), 5, 8);
namedWindow( "Contours", 0 );
imshow( "Contours", img );
因为'等高线'是矢量&gt;,contours.push_back(var) - &gt; var应该是一个向量
谢谢!我已经学会了一个错误
答案 1 :(得分:1)
在您的第一个示例中,您创建了一系列包含单个元素的点四人组。序列elem_size
应为sizeof(CvPoint)
(不要乘以4)并逐个添加点:
CvMemStorage *memStorage = cvCreateMemStorage(0);
// without these flags the drawContours() method does not consider the sequence
// as contour and just draws nothing
CvSeq* seq = cvCreateSeq(CV_32SC2 | CV_SEQ_KIND_CURVE,
sizeof(CvSeq), sizeof(CvPoint), memStorage);
cvSeqPush(cvPoint(10, 10));
cvSeqPush(cvPoint(1, 1));
cvSeqPush(cvPoint(20, 50));
请注意,您无需插入最后一个点来绘制轮廓,轮廓会自动关闭。