在OpenCV3.0+Visual Studio 2015下可运行
#include <iostream>
#include <string>
#include<cv.h>
#include<highgui.h>
using namespace std;
/* 轮廓检测代码 */
int main()
{
IplImage* src = NULL;
IplImage* img = NULL;
IplImage* dst = NULL;
CvMemStorage* storage = cvCreateMemStorage(0);;
CvSeq* contour = 0;
int contours = 0;
CvScalar external_color;
CvScalar hole_color;
src = cvLoadImage("C:\\Users\\Ediven\\Documents\\Visual Studio 2015\\Projects\\testOpenCV\\testOpenCV\\circles.jpg", 1);
img = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);//灰度图
dst = cvCreateImage(cvGetSize(src), src->depth, src->nChannels);//输出
/* 灰度化 */
cvCvtColor(src, img, CV_BGR2GRAY);
/* 二值化 */
cvThreshold(img, img, 100, 200, CV_THRESH_BINARY);
/* 轮廓检测 */
contours = cvFindContours(img, storage, &contour, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
/* cvDrawContours绘制 */
for (; contour != 0; contour = contour->h_next)
{
external_color = CV_RGB(rand() & 255, rand() & 255, rand() & 255);
hole_color = CV_RGB(rand() & 255, rand() & 255, rand() & 255);
cvDrawContours(dst, contour, external_color, hole_color, 1, 2, 8);
}
cvNamedWindow("Contour", 1);
cvShowImage("Contour", dst);
cvWaitKey(0);
cvReleaseMemStorage(&storage);
cvReleaseImage(&src);
cvReleaseImage(&img);
cvReleaseImage(&dst);
return 0;
}
运行结果: