查找轮廓并获取最大轮廓的所有点

从二值化处理过后的图像中,获取最大轮廓,并将其保存到ContourPoint里面。

GetContours(IplImage const* const src, std::vector<CvPoint>& ContourPoint)
{
	IplImage* temp=cvCreateImage(cvGetSize(src),src->depth, src->nChannels);
	cvCopy(src,temp);
	
	CvSeq* temp_contours = NULL;
	CvSeq* MaxContours = NULL;
	CvMemStorage* storage = cvCreateMemStorage(0);//开辟默认大小的空间
	cvFindContours(temp, storage, &temp_contours, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, cvPoint(0, 0));
	
	int maxsize = 20;
	int cnt = 0;
	IplImage* temp2 = cvCreateImage(cvGetSize(temp),8,3);
	for(;temp_contours!=NULL;temp_contours=temp_contours->h_next)
	{
		CvSeq* temp_contour = NULL;
		temp_contour = temp_contours;
		unsigned int tempsize = temp_contour->total;
		//得到最大轮廓
		if (tempsize > maxsize)
		{
			MaxContours = temp_contours;
			maxsize = tempsize;
			cvDrawContours(temp2, temp_contours, CV_RGB(255, 255, 255), CV_RGB(255, 255, 255), 0, 2, CV_FILLED, cvPoint(0, 0));  //CV_FILLED
			cnt++;
		}
	}
	int pointx,pointy;
	int pi;
	for(pi=0;pi<maxsize;pi++)
	{  
		CvPoint* p=(CvPoint*)cvGetSeqElem(MaxContours,pi); 
		pointx = p->x;
		pointy = p->y;
		if (pointy < temp2->height+1)
		{
			ContourPoint.push_back(cvPoint(pointx,pointy));
		}
	}
	cvReleaseMemStorage(&storage);
	cvReleaseImage(&temp);
	cvReleaseImage(&temp2);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/kai69/article/details/78415806