Image.canny#
- Image.canny(sigma: float | None = None, th0: float | None = None, th1: float | None = None, percentile: float = 90, k: float = 0.5, hist: bool = False) Any[source]#
Canny edge detection
- Parameters:
sigma – standard deviation of a Gaussian used to smooth the image before edge detection, defaults to None (no smoothing)
th0 – lower hysteresis threshold, defaults to None
th1 – upper hysteresis threshold, defaults to None
percentile – percentile of the gradient magnitude used as the upper threshold when no threshold is given, defaults to 90
k – ratio of the lower threshold to the upper threshold, defaults to 0.5
hist – also return a histogram of the gradient magnitude, defaults to False
- Raises:
ValueError – a threshold is given as well as a non-default
percentile- Returns:
edge image, or edge image and gradient histogram if
histis True
Computes an edge image obtained using the Canny edge detector algorithm. Hysteresis filtering is applied to the gradient image: edge pixels >
th1are connected to adjacent pixels >th0, those belowth0are set to zero.The thresholds apply to the gradient magnitude computed by OpenCV, which is \(|G_x| + |G_y|\) where \(G_x\) and \(G_y\) are the outputs of the 3x3 Sobel kernels applied to the image after conversion to
uint8. This is not normalized, so a step of height 255 gives a gradient of 1020.The thresholds are set in one of two ways:
Explicitly.
th0andth1are passed to OpenCV. If only one is given the other is set usingk:th0 = k * th1orth1 = th0 / k.Automatically, if neither is given. The upper threshold is the
percentileof the gradient magnitude of the (optionally smoothed) image, and the lower threshold isktimes that. A percentile of 80 to 90 is typical.
With
hist=Truethe gradient magnitude, which is the quantity that is thresholded, is also returned as aCannyHistogram. Its attributesth0andth1are the thresholds that were used, and itsplotmethod shows them on the histogram. This helps in choosing thresholds.Examples
Note
Produces a zero image with single pixel wide edges having non-zero values.
A color image is automatically converted to greyscale first.
Changed in version 2.5.0:
sigma,th0andth1now take effect. Previously they were ignored and the thresholds were always set from the mean of the image.sigmanow defaults to None, no smoothing. The automatic thresholds are now set from thepercentileof the gradient magnitude andk. The argumentspercentile,kandhistare new.References
“A Computational Approach To Edge Detection”, J. Canny, IEEE Trans. Pattern Analysis and Machine Intelligence, 8(6):679–698, 1986.
P. Corke, Robotics, Vision & Control for Python, Springer, 2023, Section 11.5.1.3.