- #include
- "opencv2/imgcodecs.hpp"
- #include "opencv2/highgui.hpp"
- #include "opencv2/imgproc.hpp"
- using namespace cv;
- using namespace std;
- Mat src,src_gray;
- int
- thresh =
- 100;
- int
- max_thresh =
- 255;
- RNG rng(12345);
- void
- thresh_callback(
- int
- ,
- void
- *
- );
- int
- main(
- int
- ,
- char
- **
- argv )
- {
- // 读图
- src = imread(
- "Pillnitz.jpg", IMREAD_COLOR);
- if (src.empty())
- return
- -
- 1;
- // 转化为灰度图
- cvtColor(src, src_gray, COLOR_BGR2GRAY );
- blur(src_gray, src_gray, Size(3
- ,
- 3) );
- // 显示
- namedWindow(
- "Source", WINDOW_AUTOSIZE );
- imshow( "Source", src );
- // 滑动条
- createTrackbar(
- "Canny thresh:"
- ,
- "Source"
- , &
- thresh, max_thresh, thresh_callback );
- // 回调函数
- thresh_callback(
- 0
- ,
- 0 );
- waitKey(0);
- }
- // 回调函数
- void
- thresh_callback(
- int
- ,
- void
- *
- )
- {
- Mat canny_output;
- vector
- >
- contours;
- vector
- hierarchy;
- // canny 边缘检测
- Canny(src_gray, canny_output, thresh, thresh*
- 2
- ,
- 3);
- // 寻找轮廓
- findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(
- 0
- ,
- 0) );
- Mat drawing
- =
- Mat::zeros( canny_output.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( drawing, contours, (int
- )i, color,
- 2
- ,
- 8
- , hierarchy,
- 0, Point() );
- }
- namedWindow( "Contours", WINDOW_AUTOSIZE );
- imshow( "Contours", drawing );
- }
来源: http://www.cnblogs.com/xinxue/p/5350746.html