查找轮廓 | void cv::findContours() |
绘制轮廓 | void cv::drawContours() |
轮廓
轮廓可以简单地解释为连接具有相同颜色或强度的所有连续点(沿边界)的曲线。
详情:opencv学习(四十)之寻找图像轮廓findContours()
【OpenCV3】图像轮廓查找与绘制——cv::findContours()与cv::drawContours()详解
1.找到轮廓cv::findContours()
void cv::findContours(
cv::InputOutputArray image, // 输入的8位单通道“二值”图像
cv::OutputArrayOfArrays contours, // 包含points的vectors的vector
cv::OutputArray hierarchy, // (可选) 拓扑信息
int mode, // 轮廓检索模式
int method, // 近似方法
cv::Point offset = cv::Point() // (可选) 所有点的偏移
);
void cv::findContours(
cv::InputOutputArray image, // 输入的8位单通道“二值”图像
cv::OutputArrayOfArrays contours, // 包含points的vectors的vector
int mode, // 轮廓检索模式
int method, // 近似方法
cv::Point offset = cv::Point() // (可选) 所有点的偏移
);
2.绘制轮廓cv::drawContours()
void cv::drawContours(
cv::InputOutputArray image, // 用于绘制的输入图像
cv::InputArrayOfArrays contours, // 点的vectors的vector
int contourIdx, // 需要绘制的轮廓的指数 (-1 表示 "all")
const cv::Scalar& color, // 轮廓的颜色
int thickness = 1, // 轮廓线的宽度
int lineType = 8, // 轮廓线的邻域模式('4'邻域 或 '8'邻域)
cv::InputArray hierarchy = noArray(), // 可选 (从 findContours得到)
int maxLevel = INT_MAX, // 轮廓中的最大下降
cv::Point offset = cv::Point() // (可选) 所有点的偏移
)
代码
#include<opencv2/opencv.hpp>
#include<iostream>
#include<imgproc.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat image = imread("C:/Users/YY/Pictures/Saved Pictures/1.jpg");
Mat dst1, dst2;
vector<vector<Point>>contours;
vector<Vec4i>hierarchy;
imshow("原图", image);
cvtColor(image, dst1,COLOR_BGR2GRAY);
imshow("灰度", dst1);
threshold(dst1, dst1, 140, 255, THRESH_BINARY);
//Canny(dst1, dst1, 10, 150);
imshow("二值", dst1);
//查找轮廓
findContours(dst1, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
dst1 = Scalar(0, 0, 0);
drawContours(dst1, contours, -1, (255, 255, 255), 1);
imshow("轮廓1", dst1);
dst1 = Mat::zeros(image.size(), CV_8UC3);
for (int i = 0; i < hierarchy.size(); i++) {
Scalar color = Scalar(rand() % 255, rand() % 255, rand() % 255);
drawContours(dst1, contours, i, color, FILLED, 8, hierarchy);
}
imshow("轮廓2", dst1);
waitKey(0);
destroyAllWindows();
return 0;
}