OpenCV轮廓提取

相应的轮廓提取分为以下两部分:

1、cvThreshold(pImg, pImg, 150, 255, CV_THRESH_BINARY);

     cvShowImage("threshold", pImg);

   对图像进行二值化,显示相应的图像

2、cvFindContours(pImg, storage, &contour, sizeof(CvContour),

    mode, CV_CHAIN_APPROX_SIMPLE, cvPoint(0, 0));

    查找相应的轮廓

    cvDrawContours(pContourImg, contour,
CV_RGB(0, 0, 255), CV_RGB(255, 0, 0),

2, 2, 8, cvPoint(0, 0));

    画出相应的轮廓

代码如下:

IplImage* pImg = NULL;
		IplImage* pContourImg = NULL;

		CvMemStorage * storage = cvCreateMemStorage(0);
		CvSeq * contour = 0;
		int mode = CV_RETR_EXTERNAL;

		if (argc == 3)
		if (strcmp(argv[2], "all") == 0)
		mode = CV_RETR_CCOMP; //内外轮廓都检测  


		////创建窗口  
		cvNamedWindow("src", 1);
		cvNamedWindow("contour", 1);
		cvNamedWindow("threshold", 1);

		argv[1] = "e:\\test.bmp";
		////载入图像,强制转化为Gray  
		if ((pImg = cvLoadImage(argv[1], 0)) != 0)
		{

			cvShowImage("src", pImg);

			//为轮廓显示图像申请空间  
			//3通道图像,以便用彩色显示  
			pContourImg = cvCreateImage(cvGetSize(pImg),
				IPL_DEPTH_8U,
				3);
			//copy source image and convert it to BGR image  
			cvCvtColor(pImg, pContourImg, CV_GRAY2BGR);
		//	//----阈值分割-------------------------------------------  
			cvThreshold(pImg, pImg, 150, 255, CV_THRESH_BINARY);
			cvShowImage("threshold", pImg);
		//	//-----------------------------------------------  
		//	//查找contour----------------输入必须是二值图像  
			cvFindContours(pImg, storage, &contour, sizeof(CvContour),
				mode, CV_CHAIN_APPROX_SIMPLE, cvPoint(0, 0));

		}
		else
		{
			//销毁窗口  
			cvDestroyWindow("src");
			cvDestroyWindow("contour");
			cvReleaseMemStorage(&storage);

			return -1;
		}
		////将轮廓画出      
		cvDrawContours(pContourImg, contour,
			CV_RGB(0, 0, 255), CV_RGB(255, 0, 0),
			2, 2, 8, cvPoint(0, 0));
		////显示图像  
		cvShowImage("contour", pContourImg);

		cvWaitKey(0);
		////销毁窗口  
		cvDestroyWindow("src");
		cvDestroyWindow("contour");
		////释放图像  
		cvReleaseImage(&pImg);
		cvReleaseImage(&pContourImg);

		cvReleaseMemStorage(&storage);

		return 0;

输入的图像为 argv[1] 参数1

输出结果如下图所示:

原图:

OpenCV轮廓提取_第1张图片

二值图:

OpenCV轮廓提取_第2张图片

轮廓图:

OpenCV轮廓提取_第3张图片

你可能感兴趣的:(opencv)