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实现栈的方法
May 26 Python
python数据结构之图深度优先和广度优先实例详解
Jul 08 Python
详解Python命令行解析工具Argparse
Apr 20 Python
Python科学画图代码分享
Nov 29 Python
python基础学习之如何对元组各个元素进行命名详解
Jul 12 Python
selenium中get_cookies()和add_cookie()的用法详解
Jan 06 Python
Python自动采集微信联系人的实现示例
Feb 28 Python
pycharm新建Vue项目的方法步骤(图文)
Mar 04 Python
keras模型保存为tensorflow的二进制模型方式
May 25 Python
Python日志器使用方法及原理解析
Sep 27 Python
详解tensorflow之过拟合问题实战
Nov 01 Python
详解Python+OpenCV进行基础的图像操作
Feb 15 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分页函数代码(简单实用型)
2010/12/02 PHP
Php header()函数语法及使用代码
2013/11/04 PHP
解决PHP里大量数据循环时内存耗尽的方法
2015/10/10 PHP
Yii2.0多文件上传实例说明
2017/07/24 PHP
jQuery 各种浏览器下获得日期区别
2008/12/22 Javascript
jQuery简单tab切换效果实现方法
2015/04/08 Javascript
js实现的早期滑动门菜单效果代码
2015/08/27 Javascript
jQuery实现监控页面所有ajax请求的方法
2015/12/10 Javascript
聊一聊JS中的prototype
2016/09/29 Javascript
vue.js学习笔记之绑定style样式和class列表
2016/10/31 Javascript
BootStrap 图标icon符号图标glyphicons不正常显示的快速解决办法
2016/12/08 Javascript
jQuery使用正则表达式替换dom元素标签用法示例
2017/01/16 Javascript
Bootstrap Table使用整理(五)之分页组合查询
2017/06/09 Javascript
详解AngularJS 模块化
2017/06/14 Javascript
基于openlayers4实现点的扩散效果
2020/08/17 Javascript
微信小程序实现文字从右向左无限滚动
2020/11/18 Javascript
用Python制作简单的钢琴程序的教程
2015/04/01 Python
在Python中使用PIL模块对图片进行高斯模糊处理的教程
2015/05/05 Python
Python用Pillow(PIL)进行简单的图像操作方法
2017/07/07 Python
对numpy中的数组条件筛选功能详解
2018/07/02 Python
利用python Selenium实现自动登陆京东签到领金币功能
2019/10/31 Python
Django框架模板用法入门教程
2019/11/04 Python
在OpenCV里使用Camshift算法的实现
2019/11/22 Python
python飞机大战pygame游戏背景设计详解
2019/12/17 Python
python Manager 之dict KeyError问题的解决
2019/12/21 Python
pytorch AvgPool2d函数使用详解
2020/01/03 Python
python-jwt用户认证食用教学的实现方法
2021/01/19 Python
英国口碑最好的的维他命胶囊品牌:Myvitamins(有中文站)
2016/12/03 全球购物
New Era英国官网:美国棒球帽品牌
2018/03/21 全球购物
DC Shoes俄罗斯官网:美国滑板鞋和服饰品牌
2020/08/19 全球购物
《登鹳雀楼》教学反思
2014/04/09 职场文书
会计电算化实训报告
2014/11/04 职场文书
小学母亲节活动总结
2015/02/10 职场文书
中秋节慰问信
2015/02/15 职场文书
2015年除四害工作总结
2015/07/23 职场文书
读鲁迅先生的经典名言
2019/08/20 职场文书