Automatic calculation of low and high thresholds for the Canny operation in opencv

image-processing, opencv

Solution

I stumbled upon this answer while I was searching for a way to automatically compute Canny's threshold values.

Hope this helps anyone who comes looking for a good method for determining automatic threshold values for Canny's algorithm...

If your image consists of distinct foreground and background, then the edge of foreground object can use extracted by following:

Calculate Otsu's threshold using:

double otsu_thresh_val = cv::threshold(
    orig_img, _img, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU
);

We don't need the `_img`. We are interested in only the `otsu_thresh_val` but unfortunately, currently there is no method in OpenCV which allows you to compute only the threshold value.

Use the Otsu's threshold value as higher threshold and half of the same as the lower threshold for Canny's algorithm.

double high_thresh_val  = otsu_thresh_val,
       lower_thresh_val = otsu_thresh_val * 0.5;
cv::Canny( orig_img, cannyOP, lower_thresh_val, high_thresh_val );

More information related to this can be found in this paper: The Study on An Application of Otsu Method in Canny Operator. An explaination of Otsu's implementation can be found here.

Problem

In OpenCV, the low and high thresholds for the canny operator are mandatory: ``` cvCanny(input,output,thresh1,thresh2) ``` In Matlab, there's an option to calculate those automatically: ``` edge(input,'canny') ``` I've looked into Matlab's code for edge, and this is really not straight forward to calculate those automatically. Are you aware of any implementation of the canny operator along with automatic threshold calculation for OpenCV?

Original source