Introduction

The Canny edge detection algorithm identifies edges by looking for local maxima of the gradient of the image. It involves noise reduction, gradient calculation, non-maximum suppression, and hysteresis thresholding to yield precise edge maps.

Prerequisites

Install OpenCV and configure your C++ build system. Use pkg-config or CMake to find OpenCV libraries and headers.


// Example build command
 g++ canny.cpp -o canny `pkg-config --cflags --libs opencv4`
        

Implementation Steps

Implement Canny edge detection in the following sequence:


#include 
#include 


int main(int argc, char** argv) {
if (argc < 2) {
std::cerr << “Usage: “ << argv[0] << “ \n”;
return -1;
}

// Load the image in grayscale
cv::Mat src = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);
if (src.empty()) {
    std::cerr << "Error: Cannot load image\n";
    return -1;
}

// Reduce noise with Gaussian blur
cv::Mat blurred;
cv::GaussianBlur(src, blurred, cv::Size(5, 5), 1.5);

// Define thresholds
double lowThreshold = 50.0;
double highThreshold = 150.0;

// Perform Canny edge detection
cv::Mat edges;
cv::Canny(blurred, edges, lowThreshold, highThreshold);

// Display results
cv::imshow("Original", src);
cv::imshow("Edges", edges);
cv::waitKey(0);

return 0;

}




  

Parameters Explained

ParameterTypeDescription
lowThreshold double Lower boundary for hysteresis thresholding.
highThreshold double Upper boundary for hysteresis thresholding.
apertureSize int Size of the Sobel operator kernel (optional).
L2gradient bool Use more accurate L2 norm (optional).

Hysteresis Thresholding

Hysteresis thresholding uses two thresholds: lowThreshold and highThreshold. Pixels with gradient magnitudes above the high threshold are marked as strong edges, while pixels below the low threshold are discarded. Pixels between the thresholds are considered weak edges and are only included if they are connected to strong edges, ensuring that edges are continuous and accurate.

Result Visualization

Original image Canny edges output

Common Pitfalls and Tips

Ensure the input image is grayscale for best results.

Adjust Gaussian kernel size to reduce noise without losing edge detail.

Tune threshold values based on image contrast and noise levels.

Summary

This guide demonstrates how to apply Canny edge detection using C++ and OpenCV. Experiment with thresholds and kernels to optimize edge detection for your images.