如何在Opencv和C中找到图像轮廓的角坐标

时间:2012-05-30 17:33:57

标签: c image-processing opencv computer-vision

我必须找到一个图像的角点,以便我可以将它裁剪成矩形。我已经找到了轮廓并在其上使用了approxpoly()函数。现在如何找到轮廓的角坐标? 这是我的C代码 - >

#include <cv.h>
#include <highgui.h>

int main(int argc, char** argv)
{
IplImage *img,*gray;

if((img = cvLoadImage("save.jpg", 1)) == NULL)
{
    printf("A Img open error\n");
}

gray=cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );
cvCvtColor(img,gray,CV_BGR2GRAY);

IplImage* out_median = cvCreateImage(cvGetSize(gray),IPL_DEPTH_8U,1);
cvSmooth( gray,out_median,CV_MEDIAN,3);

IplImage* out_threshold = cvCreateImage( cvGetSize(out_median), out_median->depth, 1);
cvThreshold(out_median,out_threshold,1,255,CV_THRESH_BINARY);

CvMemStorage* storage = cvCreateMemStorage();
CvSeq* first_contour = NULL;

cvFindContours(out_threshold,storage,&first_contour,sizeof(CvContour),CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE);

CvSeq* approx_polygon = NULL;
approx_polygon=cvApproxPoly(first_contour,sizeof(CvContour),storage,CV_POLY_APPROX_DP,0.01*cvArcLength(first_contour,CV_WHOLE_SEQ, 1),0);

    //cvDrawContours(out_threshold,approx_polygon,cvScalarAll(255),cvScalarAll(255),100);
//cvShowImage("Contours", out_threshold );
//cvSaveImage("save_approxpoly_contour.jpg",out_threshold);


cvWaitKey(0);
return 0;

}

应用Approxpoly()后我的Contour Image enter image description here

1 个答案:

答案 0 :(得分:0)

我建议使用cvBlob

获取blob:

cvThreshold(&src, &dst, 10, 255, CV_THRESH_BINARY);
IplImage *labelImg = cvCreateImage(cvGetSize(&dst),IPL_DEPTH_LABEL,1);
CvBlobs blobs;
unsigned int result = cvLabel(&dst, labelImg, blobs);

如果您有多个项目,请找到限制

int borders[4];
borders[0] = 99999; //left
borders[1] = 99999; //top
borders[2] = 0;  //right
borders[3] = 0;  //bottom

for (CvBlobs::const_iterator it=blobs.begin(); it!=blobs.end(); ++it)
{   
    if((*it).second->maxx) < borders[0]){
        borders[0] = (*it).second->maxx; 
    }
    if(((*it).second->miny) < borders[1]){
        borders[1] = (*it).second->miny;
    }
    if((*it).second->minx) > borders[2]){
        borders[2] = (*it).second->minx;
    }
    if(((*it).second->maxy) > borders[3]){
        borders[3] = (*it).second->maxy;
    }
}