OpenCV 快速連通區域分析


 

(1)cv::connectedComponents()

1 int nccomps=connectedComponents ( 2  cv::InputArrayn image, 3  cv::OutputArray labels, 4         int connectivity = 8, 5        int ltype = CV_32S );

函數返回值nccomps為int型,表示連通域個數;

image: 輸入圖像(8-bit,單通道圖像)

lables:  生成的標記圖,部分截圖如下圖所示,labelsde 尺寸和輸入圖像大小相等

connetivity: 表示4或8鄰域連接(int型)

ltype:  表示輸出標記圖的類型(CV_32S,CV_16U)

 (2)cv::connectedComponentsWithStats()函數(2)增加了一下重要信息,包圍框(bounding box)、面積和質心等。

1 int  nccomps=connectedComponentsWithStats ( 2  cv::InputArrayn image, 3  cv::OutputArray labels, 4  cv::OutputArray stats, 5  cv::OutputArray centroids, 6     int  connectivity = 8, 7     int   ltype= CV_32S 8     );

image: 輸入圖像(8-bit,單通道圖像)

lables:  生成的標記圖,部分截圖如下圖所示,labelsde 尺寸和輸入圖像大小相等

star:一個5*nccomps的矩陣,分別對應各個輪廓的x,y,width,height和面積

centroids:一個2*nccomps的居住,表示每個連通域的質心

connetivity: 表示4或8鄰域連接(int型)

ltype:  表示輸出標記圖的類型(CV_32S,CV_16U)

star輸出圖:

話不多說上源碼:(面積小於3000的置零)

 1 #include <algorithm>
 2 #include <iostream>
 3 #include<opencv2/opencv.hpp>
 4 using namespace cv;  5 using namespace std;  6 
 7 int main()  8 {  9 
10  Mat img, img_edge, labels, centroids, img_color, stats; 11     img = imread("C:\\Users\\hsy\\Desktop\\3.jpg", 0); 12     threshold(img, img_edge, 0, 255, THRESH_OTSU); 13     int nccomps = connectedComponentsWithStats(img_edge, labels, stats, centroids); 14     cout << "連通域個數: " << nccomps << endl; 15     vector<Vec3b>colors(nccomps + 1);; 16     colors[0] = Vec3b(0, 0, 0); 17     for (int i = 1; i <= nccomps; i++) 18  { 19         colors[i] = Vec3b(rand() % 256, rand() % 256, rand() % 256); 20         if (stats.at<int>(i, CC_STAT_AREA) < 2500) 21             colors[i] = Vec3b(0, 0, 0); 22 
23         cout << stats.at<int>(i - 1, CC_STAT_AREA) << endl;//連通域的面積
24         
25  } 26     img_color = Mat::zeros(img.size(), CV_8UC3); 27     for (int y = 0; y < img_color.rows; y++) 28         for (int x = 0; x < img_color.cols; x++) 29  { 30             int label = labels.at<int>(y, x); 31             CV_Assert(0 <= label && label <= nccomps); 32             img_color.at<Vec3b>(y, x) = colors[label]; 33  } 34 
35     imshow("Labeled map", img_color); 36     imshow("img", img); 37  waitKey(); 38     return 0; 39 }

    

 


免責聲明!

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



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