OpenCV获取联通区域轮廓
检测联通区域,主要是利用opencv的findContours函数来获取连通域的外轮廓点的集合,然后可以用drawContours来描绘这些点。需要注意的是,findContours函数的输入图像必须是单通道二值图的格式。
此外,在很多情况下我们需要获取连通域的最小外接矩形,使用boundingRect函数配合findContours函数来使用即可达到目的。
代码如下:
- #include "stdafx.h"
- #include <opencv2\opencv.hpp>
- #include <iostream>
- #include <vector>
- using namespace cv;
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- Mat srcimage, grayimage, dstimage;
- // RGB原图
- srcimage = imread("D:\\image.jpg");
- // 灰度图并二值化
- cvtColor(srcimage, grayimage, CV_RGB2GRAY);
- threshold(grayimage, dstimage, 200, 255, THRESH_BINARY_INV);
- // 搜索连通域轮廓
- vector<std::vector<cv::Point>> contours;
- vector<Vec4i> hierarchy;
- findContours(dstimage, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
- drawContours(srcimage, contours, -1, Scalar(0, 0, 255), 2); //> 在RGB图像画出轮廓
- // 最小外接矩形
- for (int index = 0; index >= 0; index = hierarchy[index][0])
- {
- // 若图像内不存在联通域,则不进行后去步骤
- if (contours.size() == 0)
- {
- break;
- }
- // 最小外接矩形
- Rect rect = boundingRect(contours[index]);
- rectangle(srcimage, rect, Scalar(255, 0, 0), 2, 8, 0);
- imshow("【srcimage】", srcimage);
- imwrite("D:\\dst.jpg", srcimage);
- waitKey(0);
- }
- return 0;
- }
待检测的原图:
得到的连通域轮廓:
连通域最小外接矩形:(如果只想要矩形框,可以注销掉drawContours函数,则不会画出连通域轮廓)