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 hist is True

Computes an edge image obtained using the Canny edge detector algorithm. Hysteresis filtering is applied to the gradient image: edge pixels > th1 are connected to adjacent pixels > th0, those below th0 are 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:

  1. Explicitly. th0 and th1 are passed to OpenCV. If only one is given the other is set using k: th0 = k * th1 or th1 = th0 / k.

  2. Automatically, if neither is given. The upper threshold is the percentile of the gradient magnitude of the (optionally smoothed) image, and the lower threshold is k times that. A percentile of 80 to 90 is typical.

With hist=True the gradient magnitude, which is the quantity that is thresholded, is also returned as a CannyHistogram. Its attributes th0 and th1 are the thresholds that were used, and its plot method shows them on the histogram. This helps in choosing thresholds.

Examples

>>> from machinevisiontoolbox import Image
>>> img = Image.Read('monalisa.png')
>>> edges = img.canny()
>>> edges = img.canny(sigma=2, percentile=80)
>>> edges = img.canny(th0=100, th1=300)
>>> edges, h = img.canny(hist=True)
>>> h.th0, h.th1
(66.0, 132.0)

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, th0 and th1 now take effect. Previously they were ignored and the thresholds were always set from the mean of the image. sigma now defaults to None, no smoothing. The automatic thresholds are now set from the percentile of the gradient magnitude and k. The arguments percentile, k and hist are new.

References

See also

smooth Histogram