资源简介

OpenCV2.4.10版本实现OpenCV新增connectedComponentsWithStats函数

资源截图

代码片段和文件信息

//OpenCV3.3.0

#include 
#include 
#include
#include “m_precomp.hpp“
using namespace cv;
using namespace std;


Mat findMaxContours(Mat src)
{
Mat bw; src.copyTo(bw);
//查找最大连通区域
vector>contours;  //每个轮廓中的点
vectorhierarchy;         //轮廓的索引  
findContours(bw contours hierarchy CV_RETR_EXTERNAL CHAIN_APPROX_SIMPLE Point());
double max_area = 0;
int index = 0;
for (int i = 0; i < contours.size(); i++)
{
if (contourArea(contours[i]) > max_area)
{
max_area = contourArea(contours[i]);
index = i;
}
}
Mat dstImage = Mat::zeros(src.rows src.cols CV_8UC1);
if (contours.size() > 0)
{
drawContours(dstImage contours index Scalar(255) -1);
}
contours.clear();
hierarchy.clear();
contours.swap(vector>(contours));
hierarchy.swap(vector(hierarchy));
return dstImage;
//RotatedRect rect_Pointer = minAreaRect(contours[index]);
//cv::Point2f* vertices = new cv::Point2f[4];
//rect_Pointer.points(vertices);
//std::vector contourRect;
//for (int i = 0; i < 4; i++)
//{
// contourRect.push_back(vertices[i]);
//}
//std::vector> contourRects;
//contourRects.push_back(contourRect);
//drawContours(dstImage contourRects 0 Scalar(255) -1);
}

int main()
{
Mat img img_edge labels centroids img_color stats;
img = imread(“1.png“ 0);
threshold(img img_edge 0 255 THRESH_OTSU);
int nccomps = connectedComponentsWithStats(img_edge labels stats centroids 8 CV_32S CCL_DEFAULT);
cout << “连通域个数: “ << nccomps << endl;
vectorcolors(nccomps + 1);;
colors[0] = Vec3b(0 0 0);
for (int i = 1; i <= nccomps; i++)
{
colors[i] = Vec3b(rand() % 256 rand() % 256 rand() % 256);
if (stats.at(i-1 CC_STAT_AREA) < 2500)
colors[i] = Vec3b(0 0 0);

cout << stats.at(i - 1 CC_STAT_AREA) << endl;//连通域的面积

}
img_color = Mat::zeros(img.size() CV_8UC3);
for (int y = 0; y < img_color.rows; y++)
for (int x = 0; x < img_color.cols; x++)
{
int label = labels.at(y x);
CV_Assert(0 <= label && label <= nccomps);
img_color.at(y x) = colors[label];
}
return 0;
}

 属性            大小     日期    时间   名称
----------- ---------  ---------- -----  ----

     文件       2292  2020-03-11 17:13  connectedComponentsWithStats\main.cpp

     文件     249454  2020-03-11 16:41  connectedComponentsWithStats\m_connectedcomponents.cpp

     文件       5834  2020-03-11 16:42  connectedComponentsWithStats\m_precomp.hpp

     目录          0  2020-03-11 17:10  connectedComponentsWithStats

----------- ---------  ---------- -----  ----

               257580                    4


评论

共有 条评论