首页 文章

在OpenCv中创建自定义的CvPoint序列

提问于
浏览
1

我想使用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);

也许我错误地使用了数据 . 编译器会警告错误,并且不允许push_back指向这样的向量 . 为什么??

错误是这样的:错误2错误C2664:'std :: vector <_Ty> :: push_back':无法将参数1从'cv :: Point2i'转换为'const std :: vector <_Ty>&'

2 回答

  • 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 );
    

    因为'contours'是vector>,contours.push_back(var) - > var应该是一个向量

    谢谢!我已经学会了一个bug

  • 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));
    

    注意,您无需插入最后一个点来绘制轮廓,轮廓会自动关闭 .

相关问题