OpenCV_轮廓例子

滑动条用于设置阈值,然后对采二值化后的图像提取轮廓并绘制轮廓。当控制参数的滑动条变化时,图像被更新。

View Code
 1 //首先将图像g_image转换为灰度图像。接着用g_thresh为参数进行二值化处理,得到的二值图像保存在g_gray中。
2 //cvFindContours从二值图像g_gray查找轮廓,然后将得到的轮廓用cvDrawContours函数绘制为白色得到灰度图像。
3 //最终图像在窗口中显示处理。并将在回调函数开始处申请的结构释放。
4
5 IplImage* g_image=NULL;
6 IplImage* g_gray=NULL;
7
8 int g_thresh=120;
9 CvMemStorage* g_storage=NULL;
10 void on_trackbar(int)
11 {
12 if(g_storage==NULL)
13 {
14 g_gray=cvCreateImage(cvGetSize(g_image),8,1);
15 g_storage=cvCreateMemStorage(0);
16
17 }
18 else
19 cvClearMemStorage(g_storage);
20
21 CvSeq* contours=0;
22 cvCvtColor(g_image,g_gray,CV_BGR2GRAY);
23 cvThreshold(g_gray,g_gray,g_thresh,255,CV_THRESH_BINARY);
24 cvFindContours(g_gray,g_storage,&contours);
25 cvZero(g_gray);
26 if(contours)
27 {
28 cvDrawContours(g_gray,
29 contours,
30 cvScalarAll(255),
31 cvScalarAll(255),
32 100);
33 }
34 cvShowImage("Contours",g_gray);
35 }
36 int _tmain(int argc,char** argv)
37 {
38 g_image = cvLoadImage("orange.jpg");
39 cvNamedWindow("Contours",1);
40 cvCreateTrackbar("Threshold","Contours",&g_thresh,200,on_trackbar);
41 on_trackbar(0);
42 cvWaitKey();
43 return 0;
44 }

posted on 2011-10-12 19:17  Ming明、  阅读(8482)  评论(0编辑  收藏  举报