java OPENCV 连通域, Imgproc.findContours 例子,参数说明

http://stackoverflow.com/questions/29491669/real-time-paper-sheet-detection-using-opencv-in-android/29492699#29492699

at srcImg; //you may want to apply Canny or some threshold before searching for contours
    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Mat hierarchy;
    Imgproc.findContours(srcImg, contours, hierarchy, Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
    MatOfPoint2f mat2fsrc, mat2fdst;
    Scalar color =  new Scalar(250, 250, 255);

    for (int i = 0; i < contours.size(); i++) {
        contours.get(i).convertTo(mat2fsrc, CvType.CV_32FC2);
        Imgproc.approxPolyDP(mat2fsrc, mat2fdst, 0.01 * Imgproc.arcLength(mat2fsrc, true), true);
        mat2fdst.convertTo(contours.get(i), CvType.CV_32S);
        Imgproc.drawContours(srcImg, contours, i, color, 2, 8, hierarchy, 0, new Point());
    }



===================================================================================================================================================================================================================
http://stackoverflow.com/questions/23134304/crop-out-part-from-images-findcontours-opencv-java


System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // reading image Mat image = Highgui.imread(".\testing2.jpg", Highgui.CV_LOAD_IMAGE_GRAYSCALE); // clone the image Mat original = image.clone(); // thresholding the image to make a binary image Imgproc.threshold(image, image, 100, 128, Imgproc.THRESH_BINARY_INV); // find the center of the image double[] centers = {(double)image.width()/2, (double)image.height()/2}; Point image_center = new Point(centers); // finding the contours ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Mat hierarchy = new Mat(); Imgproc.findContours(image, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); // finding best bounding rectangle for a contour whose distance is closer to the image center that other ones double d_min = Double.MAX_VALUE; Rect rect_min = new Rect(); for (MatOfPoint contour : contours) { Rect rec = Imgproc.boundingRect(contour); // find the best candidates if (rec.height > image.height()/2 & rec.width > image.width()/2) continue; Point pt1 = new Point((double)rec.x, (double)rec.y); Point center = new Point(rec.x+(double)(rec.width)/2, rec.y + (double)(rec.height)/2); double d = Math.sqrt(Math.pow((double)(pt1.x-image_center.x),2) + Math.pow((double)(pt1.y -image_center.y), 2)); if (d < d_min) { d_min = d; rect_min = rec; } } // slicing the image for result region int pad = 5; rect_min.x = rect_min.x - pad; rect_min.y = rect_min.y - pad; rect_min.width = rect_min.width + 2*pad; rect_min.height = rect_min.height + 2*pad; Mat result = original.submat(rect_min); Highgui.imwrite("result.png", result);

===================================================================================================
参数说明 (maybe c/C++)

http://blog.csdn.net/augusdi/article/details/9011477

image:
输入的 8-比特、单通道图像. 非零元素被当成 1, 0 象素值保留为 0 - 从而图像被看成二值的。为了从灰度图像中得到这样的二值图像,可以使用 cvThreshold, cvAdaptiveThreshold 或 cvCanny. 本函数改变输入图像内容。 
storage:
得到的轮廓的存储容器 
first_contour:
输出参数:包含第一个输出轮廓的指针 
header_size:
如果 method=CV_CHAIN_CODE,则序列头的大小 >=sizeof(CvChain),否则 >=sizeof(CvContour) . 
mode:
提取模式. 
CV_RETR_EXTERNAL - 只提取最外层的轮廓 
CV_RETR_LIST - 提取所有轮廓,并且放置在 list 中 
CV_RETR_CCOMP - 提取所有轮廓,并且将其组织为两层的 hierarchy: 顶层为连通域的外围边界,次层为洞的内层边界。 
CV_RETR_TREE - 提取所有轮廓,并且重构嵌套轮廓的全部 hierarchy 
method:
逼近方法 (对所有节点, 不包括使用内部逼近的 CV_RETR_RUNS). 
CV_CHAIN_CODE - Freeman 链码的输出轮廓. 其它方法输出多边形(定点序列). 
CV_CHAIN_APPROX_NONE - 将所有点由链码形式翻译(转化)为点序列形式 
CV_CHAIN_APPROX_SIMPLE - 压缩水平、垂直和对角分割,即函数只保留末端的象素点; 
CV_CHAIN_APPROX_TC89_L1, 
CV_CHAIN_APPROX_TC89_KCOS - 应用 Teh-Chin 链逼近算法. CV_LINK_RUNS - 通过连接为 1 的水平碎片使用完全不同的轮廓提取算法。仅有 CV_RETR_LIST 提取模式可以在本方法中应用. 
offset:
每一个轮廓点的偏移量. 当轮廓是从图像 ROI 中提取出来的时候,使用偏移量有用,因为可以从整个图像上下文来对轮廓做分析. 
函数 cvFindContours 从二值图像中提取轮廓,并且返回提取轮廓的数目。指针 first_contour 的内容由函数填写。它包含第一个最外层轮廓的指针,如果指针为 NULL,则没有检测到轮廓(比如图像是全黑的)。其它轮廓可以从 first_contour 利用 h_next 和 v_next 链接访问到。 在 cvDrawContours 的样例显示如何使用轮廓来进行连通域的检测。轮廓也可以用来做形状分析和对象识别 - 见CVPR2001 教程中的 squares 样例。该教程可以在 SourceForge 网站上找到。 

DrawContours 在图像中绘制外部和内部的轮廓。

[cpp] view plain copy
 
  1. void cvDrawContours( CvArr *img, CvSeq* contour,CvScalar external_color, CvScalar hole_color,int max_level, int thickness=1,int line_type=8, CvPoint offset=cvPoint(0,0) );  

img:
用以绘制轮廓的图像。和其他绘图函数一样,边界图像被感兴趣区域(ROI)所剪切。 
contour:

指针指向第一个轮廓。 
external_color:

外层轮廓的颜色。 
hole_color:

内层轮廓的颜色。 
max_level:

 绘制轮廓的最大等级。如果等级为0,绘制单独的轮廓。如果为1,绘制轮廓及在其后的相同的级别下轮廓。如果值为2,所有的轮廓。如果等级为2,绘制所有同级轮廓及所有低一级轮廓,诸此种种。如果值为负数,函数不绘制同级轮廓,但会升序绘制直到级别为abs(max_level)-1的子轮廓。 
thickness:

绘制轮廓时所使用的线条的粗细度。如果值为负(e.g. =CV_FILLED),绘制内层轮廓。 
line_type:

 线条的类型。参考cvLine. 
offset:

 照给出的偏移量移动每一个轮廓点坐标.当轮廓是从某些感兴趣区域(ROI)中提取的然后需要在运算中考虑ROI偏移量时,将会用到这个参数。 

当thickness>=0,函数cvDrawContours在图像中绘制轮廓,或者当thickness<0时,填充轮廓所限制的区域。 

[cpp] view plain copy
 
  1. #include <stdio.h>  
  2. #include <cv.h>  
  3. #include <cxcore.h>     
  4. #include <highgui.h>    
  5.   
  6. #pragma comment(lib, "cv.lib")  
  7. #pragma comment(lib, "cxcore.lib")  
  8. #pragma comment(lib, "highgui.lib")  
  9.   
  10. // 内轮廓填充     
  11. // 参数:     
  12. // 1. pBinary: 输入二值图像,单通道,位深IPL_DEPTH_8U。    
  13. // 2. dAreaThre: 面积阈值,当内轮廓面积小于等于dAreaThre时,进行填充。     
  14. void FillInternalContours(IplImage *pBinary, double dAreaThre)     
  15. {     
  16.     double dConArea;     
  17.     CvSeq *pContour = NULL;     
  18.     CvSeq *pConInner = NULL;     
  19.     CvMemStorage *pStorage = NULL;     
  20.     // 执行条件     
  21.     if (pBinary)     
  22.     {     
  23.         // 查找所有轮廓     
  24.         pStorage = cvCreateMemStorage(0);     
  25.         cvFindContours(pBinary, pStorage, &pContour, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);     
  26.         // 填充所有轮廓     
  27.         cvDrawContours(pBinary, pContour, CV_RGB(255, 255, 255), CV_RGB(255, 255, 255), 2, CV_FILLED, 8, cvPoint(0, 0));    
  28.         // 外轮廓循环     
  29.         int wai = 0;    
  30.         int nei = 0;    
  31.         for (; pContour != NULL; pContour = pContour->h_next)     
  32.         {     
  33.             wai++;    
  34.             // 内轮廓循环     
  35.             for (pConInner = pContour->v_next; pConInner != NULL; pConInner = pConInner->h_next)     
  36.             {     
  37.                 nei++;    
  38.                 // 内轮廓面积     
  39.                 dConArea = fabs(cvContourArea(pConInner, CV_WHOLE_SEQ));    
  40.                 printf("%f ", dConArea);     
  41.             }    
  42.             CvRect rect = cvBoundingRect(pContour,0);  
  43.             cvRectangle(pBinary, cvPoint(rect.x, rect.y), cvPoint(rect.x + rect.width, rect.y + rect.height),CV_RGB(255,255, 255), 1, 8, 0);  
  44.         }     
  45.   
  46.         printf("wai = %d, nei = %d", wai, nei);    
  47.         cvReleaseMemStorage(&pStorage);     
  48.         pStorage = NULL;     
  49.     }     
  50. }     
  51. int Otsu(IplImage* src)        
  52. {        
  53.     int height=src->height;        
  54.     int width=src->width;            
  55.   
  56.     //histogram        
  57.     float histogram[256] = {0};        
  58.     for(int i=0; i < height; i++)      
  59.     {        
  60.         unsigned char* p=(unsigned char*)src->imageData + src->widthStep * i;        
  61.         for(int j = 0; j < width; j++)       
  62.         {        
  63.             histogram[*p++]++;        
  64.         }        
  65.     }        
  66.     //normalize histogram        
  67.     int size = height * width;        
  68.     for(int i = 0; i < 256; i++)      
  69.     {        
  70.         histogram[i] = histogram[i] / size;        
  71.     }        
  72.   
  73.     //average pixel value        
  74.     float avgValue=0;      
  75.     for(int i=0; i < 256; i++)      
  76.     {        
  77.         avgValue += i * histogram[i];  //整幅图像的平均灰度      
  78.     }         
  79.   
  80.     int threshold;          
  81.     float maxVariance=0;        
  82.     float w = 0, u = 0;        
  83.     for(int i = 0; i < 256; i++)       
  84.     {        
  85.         w += histogram[i];  //假设当前灰度i为阈值, 0~i 灰度的像素(假设像素值在此范围的像素叫做前景像素) 所占整幅图像的比例      
  86.         u += i * histogram[i];  // 灰度i 之前的像素(0~i)的平均灰度值: 前景像素的平均灰度值      
  87.   
  88.         float t = avgValue * w - u;        
  89.         float variance = t * t / (w * (1 - w) );        
  90.         if(variance > maxVariance)       
  91.         {        
  92.             maxVariance = variance;        
  93.             threshold = i;        
  94.         }        
  95.     }        
  96.   
  97.     return threshold;        
  98. }       
  99.   
  100. int main()    
  101. {    
  102.     IplImage *img = cvLoadImage("c://temp.jpg", 0);    
  103.     IplImage *bin = cvCreateImage(cvGetSize(img), 8, 1);    
  104.   
  105.     int thresh = Otsu(img);    
  106.     cvThreshold(img, bin, thresh, 255, CV_THRESH_BINARY);    
  107.   
  108.     FillInternalContours(bin, 200);    
  109.   
  110.     cvNamedWindow("img");    
  111.     cvShowImage("img", img);    
  112.   
  113.     cvNamedWindow("result");    
  114.     cvShowImage("result", bin);    
  115.   
  116.     cvWaitKey(-1);    
  117.   
  118.     cvReleaseImage(&img);    
  119.     cvReleaseImage(&bin);    
  120.   
  121.     return 0;    
  122. }  

这种情况下,大月亮内部的两个内轮廓没有框出来。这个不是因为我的 rect框是 白色的缘故。。。。应该。

我断点试了,就 cvRectangle 了 4次···

[cpp] view plain copy
 
  1. #include <stdio.h>    
  2. #include <cv.h>  
  3. #include <highgui.h>    
  4. #include <math.h>    
  5.   
  6. #pragma comment(lib, "cv.lib")  
  7. #pragma comment(lib, "cxcore.lib")  
  8. #pragma comment(lib, "highgui.lib")  
  9.   
  10.   
  11. int main(int argc, char* argv[])    
  12. {    
  13.     IplImage *src = cvLoadImage(".\test.png", 0);    
  14.     IplImage *dsw = cvCreateImage(cvGetSize(src), 8, 1);    
  15.     IplImage *dst = cvCreateImage(cvGetSize(src), 8, 3);    
  16.     CvMemStorage *storage = cvCreateMemStorage(0);    
  17.     CvSeq *first_contour = NULL;    
  18.   
  19.     //turn the src image to a binary image    
  20.     //cvThreshold(src, dsw, 125, 255, CV_THRESH_BINARY_INV);    
  21.     cvThreshold(src, dsw, 100, 255, CV_THRESH_BINARY);    
  22.   
  23.     cvFindContours(dsw, storage, &first_contour, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);    
  24.     cvZero(dst);    
  25.     int cnt = 0;    
  26.     for(; first_contour != 0; first_contour = first_contour->h_next)    
  27.     {    
  28.         cnt++;    
  29.         CvScalar color = CV_RGB(rand()&255, rand()&255, rand()&255);    
  30.         cvDrawContours(dst, first_contour, color, color, 0, 2, CV_FILLED, cvPoint(0, 0));    
  31.         CvRect rect = cvBoundingRect(first_contour,0);  
  32.         cvRectangle(dst, cvPoint(rect.x, rect.y), cvPoint(rect.x + rect.width, rect.y + rect.height),CV_RGB(255, 0, 0), 1, 8, 0);  
  33.     }    
  34.   
  35.     printf("the num of contours : %d ", cnt);    
  36.   
  37.     cvNamedWindow( "Source", 1 );    
  38.     cvShowImage( "Source", src );    
  39.   
  40.     cvNamedWindow( "dsw", 1 );    
  41.     cvShowImage( "dsw", dsw );    
  42.   
  43.     cvNamedWindow( "Components", 1 );    
  44.     cvShowImage( "Components", dst );    
  45.   
  46.     cvReleaseMemStorage(&storage);    
  47.     cvWaitKey(-1);    
  48.   
  49.     return 0;    
  50. }    

这种情况下 内轮廓也框出来了。。。。。

看来阈值的选择与想要的结果有很大关系哦。

如何适应不同的图片呢?????????????????

还有,每幅图片里面,最大的轮廓是整幅图像,可以根据其面积最大,去除 哦~~~修改如下:

area = fabs(cvContourArea(first_contour, CV_WHOLE_SEQ)); //cal the hole's area

在写后面那个 内轮廓填充的时候,才发现, dsw 是我二值化之后的图像,很明显不应该是这样子的呀。

我把 关于 Contours 的函数删除之后 又 恢复正常了。不知道为嘛呢。 很显然查出来的轮廓是 正确二值化之后的吧。 不知道为嘛会这样显示呢。

再看另一个图的结果:

总有 9 个轮廓。

另外,计算了下,每个大轮廓内部的 小轮廓的数目 conner ,结果显示都为0.

看看第一个大五角星。 应该是把 边边作为了一个轮廓, 把 内部 黑色区域作为一个 轮廓 了吧????

还有,这幅图片 没有被当做一个大轮廓,上面那个小猫的,整幅图片被框了一下啊。。。。。。。。。。。。

另外i, 把 关于 cvFindContours && cvDrawContours 两个函数部分删除,二值化结果如下:


 ==========================================================================================================================================

 http://bbs.csdn.net/topics/391037090


向各位老师请教opencv中findContours获取轮廓大小时

回复次数:7

 
原文地址:https://www.cnblogs.com/donaldlee2008/p/5384952.html