opencv 查找连通区域 最大面积实例


Posted in Python onJune 04, 2020

今天在弄一个查找连通的最大面积的问题。

要把图像弄成黑底,白字,这样才可以正确找到。

然后调用下边的方法:

RETR_CCOMP:提取所有轮廓,并将轮廓组织成双层结构(two-level hierarchy),顶层为连通域的外围边界,次层位内层边界

#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
 
using namespace cv;
using namespace std;
 
int main( int argc, char** argv )
{
  Mat src = imread( argv[1] );
 
  int largest_area=0;
  int largest_contour_index=0;
  Rect bounding_rect;
 
  Mat thr;
  cvtColor( src, thr, COLOR_BGR2GRAY ); //Convert to gray
  threshold( thr, thr, 125, 255, THRESH_BINARY ); //Threshold the gray
  bitwise_not(thr,thr); //这里先变反转颜色
 
  vector<vector<Point> > contours; // Vector for storing contours
 
  findContours( thr, contours, RETR_CCOMP, CHAIN_APPROX_SIMPLE ); // Find the contours in the image
 
  for( size_t i = 0; i< contours.size(); i++ ) // iterate through each contour.
  {
    double area = contourArea( contours[i] ); // Find the area of contour
 
    if( area > largest_area )
    {
      largest_area = area;
      largest_contour_index = i;        //Store the index of largest contour
      bounding_rect = boundingRect( contours[i] ); // Find the bounding rectangle for biggest contour
    }
  }
 
  drawContours( src, contours,largest_contour_index, Scalar( 0, 255, 0 ), 2 ); // Draw the largest contour using previously stored index.
 
  imshow( "result", src );
  waitKey();
  return 0;
}

方法二: connectedComponentsWithStats

std::pair< int , int > MaxAreaFromSource(Mat srcImage, Mat &dstImage, int index)
{
  /*
  vector<vector<cv::Point> > contours; // Vector for storing contours
  
  int largest_area=0;
  size_t largest_contour_index=0;
  Rect bounding_rect;
  
  findContours( srcImage, contours, RETR_CCOMP, CHAIN_APPROX_SIMPLE ); // Find the contours in the image
  
  for( size_t i = 0; i< contours.size(); i++ ) // iterate through each contour.
  {
    double area = contourArea( contours[i] ); // Find the area of contour
    
    if( area > largest_area )
    {
      largest_area = area;
      largest_contour_index = i;        //Store the index of largest contour
      bounding_rect = boundingRect( contours[i] ); // Find the bounding rectangle for biggest contour
    }
  }
  
  Mat dst;
  cvtColor(srcImage, dst, CV_GRAY2RGB);
  drawContours( dst, contours,largest_contour_index, Scalar( 0, 255, 0 ), 2 ); // Draw the largest contour using previously stored index.
  imshow( "result", dst );
  waitKey();
  
  printf("%%%%%%%%%%%max area:%d\n", largest_area);
  return make_pair( largest_area, index);
  */
  
  cv::Mat img_bool, labels, stats, centroids, img_color, img_gray;
  
  //连通域计算
  int nccomps = cv::connectedComponentsWithStats (
                          srcImage, //二值图像
                          labels,   //和原图一样大的标记图
                          stats, //nccomps×5的矩阵 表示每个连通区域的外接矩形和面积(pixel)
                          centroids //nccomps×2的矩阵 表示每个连通区域的质心
                          );
  //cv::imshow("labels", labels);
  //cv::waitKey();
  
  vector<cv::Vec3b> colors(nccomps);
  colors[0] = cv::Vec3b(0,0,0); // background pixels remain black.
  
   printf( "index:%d==================\n",index );
  
  vector< int >vec_width,vec_area,vec_height;
  
  for(int label = 1; label < nccomps; ++label)
  {
    colors[label] = cv::Vec3b( (std::rand()&255), (std::rand()&255), (std::rand()&255) );
    std::cout << "Component "<< label << std::endl;
    std::cout << "CC_STAT_LEFT  = " << stats.at<int>(label,cv::CC_STAT_LEFT) << std::endl;
    std::cout << "CC_STAT_TOP  = " << stats.at<int>(label,cv::CC_STAT_TOP) << std::endl;
    std::cout << "CC_STAT_WIDTH = " << stats.at<int>(label,cv::CC_STAT_WIDTH) << std::endl;
    std::cout << "CC_STAT_HEIGHT = " << stats.at<int>(label,cv::CC_STAT_HEIGHT) << std::endl;
    std::cout << "CC_STAT_AREA  = " << stats.at<int>(label,cv::CC_STAT_AREA) << std::endl;
    std::cout << "CENTER  = (" << centroids.at<double>(label, 0) <<","<< centroids.at<double>(label, 1) << ")"<< std::endl << std::endl;
    
    int area = stats.at<int>(label,cv::CC_STAT_AREA);
    int left = stats.at<int>(label,cv::CC_STAT_LEFT);
    int top = stats.at<int>(label,cv::CC_STAT_TOP);
    int width = stats.at<int>(label,cv::CC_STAT_WIDTH);
    int height = stats.at<int>(label,cv::CC_STAT_HEIGHT);
    
    vec_area.push_back(area);
    vec_width.push_back(width);
    vec_height.push_back(height);
  }
  
  vector<int>::iterator bigwidth = std::max_element(std::begin(vec_width), std::end(vec_width));
  vector<int>::iterator bigheight = std::max_element(std::begin(vec_height), std::end(vec_height));
  vector<int>::iterator bigarea = std::max_element(std::begin(vec_area), std::end(vec_area));
  
  //printf( "area:%d------------width:%d height:%d \n", *bigarea, *bigwidth, *bigheight );
  
  //按照label值,对不同的连通域进行着色
  img_color = cv::Mat::zeros(srcImage.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<int>(y, x);
      CV_Assert(0 <= label && label <= nccomps);
      img_color.at<cv::Vec3b>(y, x) = colors[label];
    }
  
  cv::imshow("color", img_color);
  cv::waitKey();
   
  return make_pair( *bigarea , index );
}

我先用这个函数实现了一下,效果正确,还是opencv demo 是正确的,网上找了个例子,害死我了。

说明一下:方法一 比 第二种方法 运行速度快很多哦! 这一点很重要。

以上这篇opencv 查找连通区域 最大面积实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python函数学习笔记
Oct 07 Python
python进程管理工具supervisor使用实例
Sep 17 Python
简单理解Python中基于生成器的状态机
Apr 13 Python
nohup后台启动Python脚本,log不刷新的解决方法
Jan 14 Python
python生成带有表格的图片实例
Feb 03 Python
Django时区详解
Jul 24 Python
python twilio模块实现发送手机短信功能
Aug 02 Python
Python应用自动化部署工具Fabric原理及使用解析
Nov 30 Python
Python数据模型与Python对象模型的相关总结
Jan 26 Python
python ConfigParser库的使用及遇到的坑
Feb 12 Python
Python实现将多张图片合成MP4视频并加入背景音乐
Apr 28 Python
Python代码实现双链表
May 25 Python
Python中的Cookie模块如何使用
Jun 04 #Python
Python爬虫获取页面所有URL链接过程详解
Jun 04 #Python
Python中的全局变量如何理解
Jun 04 #Python
使用OpenCV获取图片连通域数量,并用不同颜色标记函
Jun 04 #Python
Python urllib2运行过程原理解析
Jun 04 #Python
Python如何生成xml文件
Jun 04 #Python
基于python代码批量处理图片resize
Jun 04 #Python
You might like
在PHP中操作Excel实例代码
2010/04/29 PHP
PHP下SSL加密解密、验证、签名方法(很简单)
2020/06/28 PHP
详谈配置phpstorm完美支持Codeigniter(CI)代码自动完成(代码提示)
2017/04/07 PHP
php中try catch捕获异常实例详解
2020/08/06 PHP
IE8 浏览器Cookie的处理
2009/01/31 Javascript
IE6/7 and IE8/9/10(IE7模式)依次隐藏具有absolute或relative的父元素和子元素后再显示父元素
2011/07/31 Javascript
JQuery触发事件例如click
2013/09/11 Javascript
Angular路由简单学习
2016/12/26 Javascript
浅谈regExp的test方法取得的值变化的原因及处理方法
2017/03/01 Javascript
JS完成画圆圈的小球
2017/03/07 Javascript
详解Koa中更方便简单发送响应的方式
2018/07/20 Javascript
Vue监听事件实现计数点击依次增加的方法
2018/09/26 Javascript
ES6学习笔记之字符串、数组、对象、函数新增知识点实例分析
2020/01/22 Javascript
跟老齐学Python之有容乃大的list(1)
2014/09/14 Python
Python生成随机密码
2015/03/10 Python
使用Python神器对付12306变态验证码
2016/01/05 Python
python采用django框架实现支付宝即时到帐接口
2016/05/17 Python
Python简单删除列表中相同元素的方法示例
2017/06/12 Python
python3实现TCP协议的简单服务器和客户端案例(分享)
2017/06/14 Python
使用python实现个性化词云的方法
2017/06/16 Python
pandas数值计算与排序方法
2018/04/12 Python
利用Python如何批量修改数据库执行Sql文件
2018/07/29 Python
pandas.DataFrame删除/选取含有特定数值的行或列实例
2018/11/07 Python
Python 复平面绘图实例
2019/11/21 Python
python编写俄罗斯方块
2020/03/13 Python
Python多线程:主线程等待所有子线程结束代码
2020/04/25 Python
俄罗斯优惠券网站:BIGLION
2017/05/21 全球购物
美国网上鞋子零售商:Dr. Scholl’s Shoes
2017/11/17 全球购物
中专生自荐信
2013/10/12 职场文书
《灰椋鸟》教学反思
2014/04/27 职场文书
团队精神口号
2014/06/06 职场文书
争做文明公民倡议书
2014/08/29 职场文书
2014党员学习《反腐倡廉警示教育读本》思想汇报
2014/09/13 职场文书
应届生求职自荐信范文
2015/03/04 职场文书
完美处理python与anaconda环境变量的冲突问题
2021/04/07 Python
MySQL使用IF语句及用case语句对条件并结果进行判断 
2022/09/23 MySQL