[图片] 图像连通域的标定(OpenCv版)
[图片] 图像连通域的标定(OpenCv版)
[代码] [C/C++]代码
01 | #include "cv.h" |
02 | #include "cxcore.h" |
03 | #include "highgui.h" |
04 | |
05 | int main( int argc, char ** argv ) |
06 | { |
07 | //声明IplImage指针 |
08 | IplImage* pImg = cvLoadImage( "e:/black.jpg" ,0); |
09 | IplImage* pContourImg = NULL; |
10 | CvMemStorage * storage = cvCreateMemStorage(0); |
11 | CvSeq * contour = 0; |
12 | CvSeq *contmax = 0; |
13 | int mode = CV_RETR_EXTERNAL; |
14 | cvShowImage( "src" , pImg ); |
15 | //为轮廓显示图像申请空间 |
16 | //3通道图像,以便用彩色显示 |
17 | pContourImg = cvCreateImage(cvGetSize(pImg), |
18 | IPL_DEPTH_8U, |
19 | 3); |
20 | //copy source image and convert it to BGR image |
21 | cvCvtColor(pImg, pContourImg, CV_GRAY2BGR); |
22 | //查找contour |
23 | cvFindContours( pImg, storage, &contour, sizeof (CvContour), |
24 | mode, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); |
25 | //将轮廓画出 |
26 | cvDrawContours(pContourImg, contour, |
27 | CV_RGB(255,0,0), CV_RGB(255, 0, 0), |
28 | 2, 2, 8, cvPoint(0,0)); |
29 | int area,maxArea = 10; //设面积最大值大于10Pixel |
30 | for (;contour;contour = contour->h_next) |
31 | { |
32 | area = fabs (cvContourArea( contour, CV_WHOLE_SEQ )); //获取当前轮廓面积 |
33 | printf ( "area == %lf\n" , area); |
34 | if (area > maxArea) |
35 | { |
36 | contmax = contour; |
37 | maxArea = area; |
38 | } |
39 | } |
40 | CvRect aRect = cvBoundingRect( contmax, 0 ); |
41 | cvSetImageROI( pContourImg,aRect); |
42 | //显示图像 |
43 | cvShowImage( "contour" , pContourImg ); |
44 | cvSaveImage( "e:/contour.jpg" ,pContourImg); |
45 | cvWaitKey(0); |
46 |
47 | //销毁窗口 |
48 | cvDestroyWindow( "src" ); |
49 | cvDestroyWindow( "contour" ); |
50 | //释放图像 |
51 | cvReleaseImage( &pImg ); |
52 | cvReleaseImage( &pContourImg ); |
53 | cvReleaseMemStorage(&storage); |
54 |
55 | return 0; |
56 | } |