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\n", 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\n", 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM