OpenCV获取联通区域轮廓

检测联通区域,主要是利用opencv的findContours函数来获取连通域的外轮廓点的集合,然后可以用drawContours来描绘这些点。需要注意的是, findContours函数的输入图像必须是单通道二值图的格式。
此外,在很多情况下我们需要获取连通域的最小外接矩形,使用boundingRect函数配合 findContours函数来使用即可达到目的。
代码如下:
  1. #include "stdafx.h"  
  2. #include <opencv2\opencv.hpp>  
  3. #include <iostream>  
  4. #include <vector>  
  5.   
  6. using namespace cv;  
  7. using namespace std;  
  8.   
  9. int _tmain(int argc, _TCHAR* argv[])  
  10. {  
  11.     Mat srcimage, grayimage, dstimage;  
  12.   
  13.     // RGB原图  
  14.     srcimage = imread("D:\\image.jpg");  
  15.   
  16.     // 灰度图并二值化  
  17.     cvtColor(srcimage, grayimage, CV_RGB2GRAY);  
  18.     threshold(grayimage, dstimage, 200, 255, THRESH_BINARY_INV);  
  19.   
  20.     // 搜索连通域轮廓  
  21.     vector<std::vector<cv::Point>> contours;  
  22.     vector<Vec4i> hierarchy;  
  23.     findContours(dstimage, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);   
  24.     drawContours(srcimage, contours, -1, Scalar(0, 0, 255), 2); //> 在RGB图像画出轮廓  
  25.   
  26.     // 最小外接矩形  
  27.     for (int index = 0; index >= 0; index = hierarchy[index][0])  
  28.     {  
  29.         // 若图像内不存在联通域,则不进行后去步骤  
  30.         if (contours.size() == 0)  
  31.         {  
  32.             break;  
  33.         }  
  34.   
  35.         // 最小外接矩形  
  36.         Rect rect = boundingRect(contours[index]);  
  37.         rectangle(srcimage, rect, Scalar(255, 0, 0), 2, 8, 0);  
  38.         imshow("【srcimage】", srcimage);  
  39.         imwrite("D:\\dst.jpg", srcimage);  
  40.         waitKey(0);  
  41.     }  
  42.   
  43.     return 0;  
  44. }  
待检测的原图:
OpenCV获取联通区域轮廓 - 四片叶子的三叶草 - Trifolium Linn
得到的连通域轮廓:
 
OpenCV获取联通区域轮廓 - 四片叶子的三叶草 - Trifolium Linn
连通域最小外接矩形:(如果只想要矩形框,可以注销掉 drawContours函数,则不会画出连通域轮廓
 
OpenCV获取联通区域轮廓 - 四片叶子的三叶草 - Trifolium Linn
 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值