opencv-轮廓发现
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
int threshold_value = 100;
int threshold_max = 255;
Mat src, dst;
const char* output = "findcontours-demo";
void Demo_Contours(int, void*);
RNG rng;
int main(int,void*) {
src = imread("D:/b.jpeg", 1);
if (src.empty()) {
printf("could not load image");
return -1;
}
imshow("input", src);
cvtColor(src, src, COLOR_BGR2GRAY);
namedWindow(output, WINDOW_AUTOSIZE);
const char* tarckbar_title = "threshold Value:";//滑动条
createTrackbar(tarckbar_title, output, &threshold_value, threshold_max, Demo_Contours);
Demo_Contours(0,0);
waitKey(0);
return 0;
}
void Demo_Contours(int, void*) {
Mat canny_output;
vector<vector<Point>>contours;//生成二维的点
vector<Vec4i>hierachy;
Canny(src, canny_output, threshold_value, threshold_value * 2, 3, false);
findContours(canny_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));//发现轮廓
dst = Mat::zeros(src.size(), CV_8UC3);//重新生成一个图片
RNG rng(12345);
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(dst, contours, i, color, 2, 8, hierachy, 0, Point(0, 0));//描绘轮廓
}
imshow(output, dst);
}