# Edge Detection — Computer Vision

Source: https://www.skillbyai.com/en/computer-vision/c-edges

> Find where brightness changes sharply.

## Gradients and Canny

Edges are places with large changes in brightness, often object boundaries. The **Sobel** operator estimates horizontal and vertical gradients; their magnitude highlights edges. The **Canny** detector adds smoothing, thin edges (non-maximum suppression) and **hysteresis** with two thresholds: strong edges are kept, weak ones only if connected to strong ones. Threshold choice strongly affects the result, so tune it on representative images. Edges feed shape analysis, document detection and measurement tasks.

## Sobel magnitude and Canny thresholds, run

I ran this on CPU with Python 3, OpenCV 5.0.0, scikit-image 0.26.0, PyTorch 2.14.1 and torchvision 0.29.1, using scikit-image's bundled sample photos and torchvision's published pretrained weights. On the camera photo, 5.0% of pixels have a Sobel gradient above 200. Canny marks 11.8% of pixels as edges with thresholds (50, 150), 7.5% with (100, 200) and 3.0% with (200, 300).

```python
import cv2, numpy as np
from skimage import data
img = data.camera()
gx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)
gy = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
mag = np.hypot(gx, gy)
print(f"Sobel: pixels with gradient > 200: {np.mean(mag > 200):.1%}")
for lo, hi in [(50, 150), (100, 200), (200, 300)]:
    edges = cv2.Canny(img, lo, hi)
    print(f"Canny thresholds ({lo}, {hi}): edge pixels {np.mean(edges > 0):.1%}")
```

Output:

```
Sobel: pixels with gradient > 200: 5.0%
Canny thresholds (50, 150): edge pixels 11.8%
Canny thresholds (100, 200): edge pixels 7.5%
Canny thresholds (200, 300): edge pixels 3.0%
```

## Blur before Canny on noisy images

Noise creates spurious edges; a light Gaussian blur first gives cleaner results.

**Quiz:** What happens when you raise Canny's thresholds?

- [ ] More edges appear
- [x] Fewer, stronger edges are kept
- [ ] The image becomes coloured
- [ ] Edges are blurred

*Answer:* Fewer, stronger edges are kept. Higher thresholds keep only strong gradients.
