Opencv 如何获取图像中被检测矩形的顶点

Opencv 如何获取图像中被检测矩形的顶点,opencv,rectangles,vertices,Opencv,Rectangles,Vertices,我是opencv新手,我需要检测图像中的矩形,获取其顶点,通过使用这些点,我必须裁剪图像。通过寻找轮廓来检测矩形。现在我想得到顶点的角点值。任何人都可以指导或分享代码吗 我的代码是: CvSeq* contours; //hold the pointer to a contour in the memory block CvSeq* result; //hold sequence of points of a contour CvMemStorage *storage = cvCre

我是opencv新手,我需要检测图像中的矩形,获取其顶点,通过使用这些点,我必须裁剪图像。通过寻找轮廓来检测矩形。现在我想得到顶点的角点值。任何人都可以指导或分享代码吗

我的代码是:

 CvSeq* contours;  //hold the pointer to a contour in the memory block
 CvSeq* result;   //hold sequence of points of a contour
 CvMemStorage *storage = cvCreateMemStorage(0); //storage area for all contours

 //finding all contours in the image
 cvFindContours(imgGrayScale, storage, &contours, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));

 //iterating through each contour
 while(contours)
 {
     //obtain a sequence of points of contour, pointed by the variable 'contour'
     result = cvApproxPoly(contours, sizeof(CvContour), storage, CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0);

      //if there are 4 vertices in the contour(It should be a rectangle)
     if(result->total==4 )
     {
         //iterating through each point
         CvPoint *pt[4];
         for(int i=0;i<4;i++)
            {
                pt[i] = (CvPoint*)cvGetSeqElem(result, i);
         }

         //drawing lines around the rectangle
         cvLine(img, *pt[0], *pt[1], cvScalar(0,255,0),4);
         cvLine(img, *pt[1], *pt[2], cvScalar(0,255,0),4);
         cvLine(img, *pt[2], *pt[3], cvScalar(0,255,0),4);
         cvLine(img, *pt[3], *pt[0], cvScalar(0,255,0),4);
     }
      //obtain the next contour
     contours = contours->h_next;
}

请解释你使用的代码所遇到的具体问题。因为你是OpenCV的新手,他们已经在2010切换到C++ API。请尝试使用它,而不是旧的c-api!避免使用IplImages、cv*函数,使用cv::Mat和cv::namespace中的对象。我面临的问题是,我想检测矩形的顶点,以便使用这些顶点来裁剪图像。左上角和右下角的点。@savana-我对这段代码没有问题。刚刚发布它的参考,并想知道我如何得到顶点,因为我已经检测到矩形使用轮廓函数。AFAIK,检测到的轮廓至少用C++ API保持连续点,所以矩形将不举行只有4点,但更多,所以你的代码有点让我吃惊。您确定这正确地绘制了矩形吗?