Search code examples
c++copencvimage-processingedge-detection

Get angle from OpenCV Canny edge detector


I want to use OpenCV's Canny edge detector, such as is outlined in this question. For example:

cv::Canny(image,contours,10,350); 

However, I wish to not only get the final thresholded image out, but I also wish to get the detected edge angle at each pixel. Is this possible in OpenCV?


Solution

  • canny doesn't give you this directly. However, you can calculate the angle from the Sobel transform, which is used internally in canny().

    Pseudo code:

        cv::Canny(image,contours,10,350);
        cv::Sobel(image, dx, CV_64F, 1, 0, 3, 1, 0, cv::BORDER_REPLICATE);
        cv::Sobel(image, dy, CV_64F, 0, 1, 3, 1, 0, cv::BORDER_REPLICATE);
    
        cv::Mat angle(image.size(), CV_64F)
    
        foreach (i,j) such that contours[i, j] > 0
        {
            angle[i, j] = atan2(dy[i,j], dx[i , j])
        }