轮廓发现
轮廓发现是基于图像边缘提取的基础寻找对象轮廓的方法,所以边缘提取的阈值选定会影响最终轮廓发现结果。
相关API:
findContours发现轮廓
drawContours绘制轮廓
操作步骤:
- 输入图像转为灰度图像
- 使用Canny进行边缘提取,得到二值图像
- 使用findContours寻找轮廓
- 使用drawContours绘制轮廓
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
#include <math.h>
using namespace cv;
using namespace std;
void contours(int, void *);
int thread_value = 100;
int thread_max = 255;
RNG rng;
int main(int argc, int ** argv)
{
src = imread("F:/circle.png");
if (!src.data) {
printf("无法加载图片\n");
return -1;
}
namedWindow("input img", CV_WINDOW_AUTOSIZE);
namedWindow("output img", CV_WINDOW_AUTOSIZE);
cvtColor(src, src, CV_BGR2GRAY);
imshow("input img", src);
const char* title = "thread value";
createTrackbar(title, "output img", &thread_value, thread_max, contours);
contours(0, 0);
waitKey(0);
return 0;
}
void contours(int, void *)
{
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
Canny(src, dst, thread_value, thread_value * 2, 3, false);
findContours(dst, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
Mat drawImg = Mat::zeros(dst.size(), CV_8UC3);
for (size_t i = 0; i < contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawImg, contours, i, color, 2, LINE_8, hierarchy, 0, Point(0, 0));
}
imshow("output img", drawImg);
}