1 /** 2 * @file CannyDetector_Demo.cpp 3 * @brief Sample code showing how to detect edges using the Canny Detector 4 * @author OpenCV team 5 */ 6 7 #include "opencv2/imgproc/imgproc.hpp" 8 #include "opencv2/imgcodecs.hpp" 9 #include "opencv2/highgui/highgui.hpp" 10 #include <stdlib.h> 11 #include <stdio.h> 12 13 using namespace cv; 14 15 /// Global variables 16 17 Mat src, src_gray; 18 Mat dst, detected_edges; 19 20 int edgeThresh = 1; 21 int lowThreshold; 22 int const max_lowThreshold = 100; 23 int ratio = 3; 24 int kernel_size = 3; 25 const char* window_name = "Edge Map"; 26 27 /** 28 * @function CannyThreshold 29 * @brief Trackbar callback - Canny thresholds input with a ratio 1:3 30 */ 31 static void CannyThreshold(int, void*) 32 { 33 /// Reduce noise with a kernel 3x3 34 blur( src_gray, detected_edges, Size(3,3) ); 35 36 /// Canny detector 37 Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size ); 38 39 /// Using Canny's output as a mask, we display our result 40 dst = Scalar::all(0); 41 42 src.copyTo( dst, detected_edges); 43 imshow( window_name, dst ); 44 } 45 46 47 /** 48 * @function main 49 */ 50 int main( int, char** argv ) 51 { 52 /// Load an image 53 src = imread( argv[1] ); 54 55 if( src.empty() ) 56 { return -1; } 57 58 /// Create a matrix of the same type and size as src (for dst) 59 dst.create( src.size(), src.type() ); 60 61 /// Convert the image to grayscale 62 cvtColor( src, src_gray, COLOR_BGR2GRAY ); 63 64 /// Create a window 65 namedWindow( window_name, WINDOW_AUTOSIZE ); 66 67 /// Create a Trackbar for user to enter threshold 68 createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold ); 69 70 /// Show the image 71 CannyThreshold(0, 0); 72 73 /// Wait until user exit program by pressing a key 74 waitKey(0); 75 76 return 0; 77 } 78