#include <opencv2/opencv.hpp> #include <iostream> using namespace std; using namespace cv; Mat src, dst, canny_src; int threshold_value = 100; int max_threshold = 255; RNG rng(12345); void demo_contours(int, void*); int main(){ src = imread("D:/photo/circle.jpg"); if (src.empty()) { cout << "open no success!" << endl; return -1; } //创建显示窗口 namedWindow("out image", WINDOW_AUTOSIZE); //显示原图片 imshow("input", src); //转换到灰度图单通道 cvtColor(src, canny_src, CV_BGR2GRAY); //创建滑块进行阈值选择 createTrackbar("threshole", "out image", &threshold_value, max_threshold, demo_contours); demo_contours(0,0); waitKey(0); return 0; } void demo_contours(int, void*){ //初始化轮廓向量和序号向量,固定的 vector<vector<Point>> contours; vector<Vec4i> hierachy; //阈值去噪声 Canny(canny_src, canny_src, threshold_value, 2* threshold_value, 3, false); //寻找轮廓 findContours(canny_src, contours, hierachy, RETR_TREE, 1); dst = Mat::zeros(src.size(), src.type()); 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("out image", dst); }