OpenCV  3.3.1-dev
Open Source Computer Vision

This program demonstrates usage of the Canny edge detector

Check the corresponding tutorial for more details

#include <stdio.h>
using namespace cv;
using namespace std;
int edgeThresh = 1;
int edgeThreshScharr=1;
Mat image, gray, blurImage, edge1, edge2, cedge;
const char* window_name1 = "Edge map : Canny default (Sobel gradient)";
const char* window_name2 = "Edge map : Canny with custom gradient (Scharr)";
// define a trackbar callback
static void onTrackbar(int, void*)
blur(gray, blurImage, Size(3,3));
// Run the edge detector on grayscale
Canny(blurImage, edge1, edgeThresh, edgeThresh*3, 3);
cedge = Scalar::all(0);
image.copyTo(cedge, edge1);
imshow(window_name1, cedge);
Mat dx,dy;
Canny( dx,dy, edge2, edgeThreshScharr, edgeThreshScharr*3 );
cedge = Scalar::all(0);
image.copyTo(cedge, edge2);
imshow(window_name2, cedge);
static void help()
printf("\nThis sample demonstrates Canny edge detection\n"
" /.edge [image_name -- Default is ../data/fruits.jpg]\n\n");
const char* keys =
"{help h||}{@image |../data/fruits.jpg|input image name}"
int main( int argc, const char** argv )
CommandLineParser parser(argc, argv, keys);
string filename = parser.get<string>(0);
image = imread(filename, IMREAD_COLOR);
printf("Cannot read image file: %s\n", filename.c_str());
return -1;
cedge.create(image.size(), image.type());
cvtColor(image, gray, COLOR_BGR2GRAY);
// Create a window
namedWindow(window_name1, 1);
namedWindow(window_name2, 1);
// create a toolbar
createTrackbar("Canny threshold default", window_name1, &edgeThresh, 100, onTrackbar);
createTrackbar("Canny threshold Scharr", window_name2, &edgeThreshScharr, 400, onTrackbar);
// Show the image
onTrackbar(0, 0);
// Wait for a key stroke; the same function arranges events processing
return 0;