Home >Backend Development >Python Tutorial >Canny Edge Detector Using Python
Edge detection is a crucial image analysis technique for object recognition based on outlines and is vital for image information recovery. It extracts key features like lines and curves, often used by advanced computer vision and image processing algorithms. A robust edge detection algorithm accurately identifies major edges while suppressing noise-induced false edges.
Edges represent significant local changes in image intensity (pixel values), typically occurring at region boundaries. This tutorial explains the Canny edge detection algorithm and its Python implementation.
The Canny Edge Detector
Named after its inventor, John F. Canny (1986), the Canny detector takes a grayscale image as input and outputs an image highlighting intensity discontinuities (edges).
The process involves:
t1
(upper) and t2
(lower), with t1 > t2
, control edge tracking. Tracking starts at points above t1
and continues until the gradient falls below t2
. Points above t1
are always edges; points below t1
but above t2
are edges only if connected to points above t1
.The Gaussian kernel width and the t1
/t2
thresholds are parameters influencing the Canny detector's output.
Python Implementation
Two methods are shown: using scikit-image
and OpenCV
.
Using scikit-image
Install scikit-image
(e.g., sudo apt-get install python-skimage
on Ubuntu). The canny()
function (in the feature
module) applies the Canny detector.
Using the sample image "boat.png" (shown below):
The code:
<code class="language-python">from skimage import io, feature im = io.imread('boat.png') edges = feature.canny(im) io.imshow(edges) io.show()</code>
The output (edge-detected image):
Parameter adjustments yield varying edge detection results.
Using OpenCV
Install OpenCV (see relevant installation guides for your operating system). OpenCV's Canny()
function performs edge detection.
The code:
<code class="language-python">from skimage import io, feature im = io.imread('boat.png') edges = feature.canny(im) io.imshow(edges) io.show()</code>
Arguments: im
(image), lower threshold (25), upper threshold (255), L2gradient=False
(uses L1-norm). matplotlib
displays the results.
The output (edge-detected image):
Conclusion
This tutorial covered the Canny edge detector and its straightforward implementation using scikit-image
and OpenCV
, demonstrating its effectiveness in edge detection.
The above is the detailed content of Canny Edge Detector Using Python. For more information, please follow other related articles on the PHP Chinese website!