DIP+CV · Programming Exercise

EP03_08 — 🧭 Sobel Gradient: Gx and Gy

3.14.8 EP03_08 🧭 Sobel Gradient: Gx and Gy

In Mars exploration rovers (such as Perseverance), obstacle detection is performed in real time by stereoscopic cameras. The Sobel operator computes the directional gradient of the scene and is used in the edge detection algorithm to identify rocks, cracks, and terrain unevenness that could compromise navigation.

See Figure 3.33 for a simulation of this EP.

3.14.8.1 📋 Implementation Guidelines

  1. Dimensions: Read the integers \(L\) (rows) and \(C\) (columns).
  2. Data: Read the matrix \(f\).
  3. Gx and Gy: For each internal pixel \((i,j)\) with \(1 \le i < L-1\), \(1 \le j < C-1\):

\[G_x(i,j) = [f(i-1,j+1) + 2f(i,j+1) + f(i+1,j+1)] - [f(i-1,j-1) + 2f(i,j-1) + f(i+1,j-1)]\]

\[G_y(i,j) = [f(i+1,j-1) + 2f(i+1,j) + f(i+1,j+1)] - [f(i-1,j-1) + 2f(i-1,j) + f(i-1,j+1)]\]

  1. Magnitude: \(|\nabla f(i,j)| = \text{clip}(\text{round}(\sqrt{G_x^2 + G_y^2}))\).
  2. Edge: Edge pixels receive magnitude 0.
  3. Output: Display the \(L \times C\) magnitude.

3.14.8.2 📌 Computational Constraints

  • Rounding: Apply round before converting to integer.
  • Saturation: \(\text{clip}(x) = \max(0, \min(255, x))\).
  • Square root: Use \(\sqrt{G_x^2 + G_y^2}\) (not the approximation \(|G_x| + |G_y|\)).

3.14.8.3 🧠 Theoretical Foundation

Operator Detects Diagonal coefficients
\(G_x\) Vertical edges \(\pm 1\)
\(G_y\) Horizontal edges \(\pm 1\)
\(|\nabla f|\) All edges Combined

3.14.8.4 📦 Input and Output Specification (VPL)

Input:

  • Line 1: Integer \(L\).
  • Line 2: Integer \(C\).
  • Following lines: Matrix elements.

Output:

  • Gradient magnitude, \(L \times C\) matrix.

3.14.8.5 📌 Examples

Input Output Observation
3
3
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
Null image: zero gradient
3
3
0 0 255
0 0 255
0 0 255
0 0 0
0 255 0
0 0 0
Central vertical edge: high Gx
🧭 Simulator EP03_08: Sobel Gradient (Gx and Gy) |∇f| = √(Gx² + Gy²)

Analyze the horizontal (Gx) and vertical (Gy) decomposition of the Sobel operator and hover over the magnitude pixels to inspect the 3×3 neighborhood.

Sobel Kernels:
−1
0
+1
−2
0
+2
−1
0
+1
Gx
−1
−2
−1
0
0
0
+1
+2
+1
Gy
Original Image f 5×5 pixel matrix
Magnitude |∇f| √(Gx² + Gy²)
Gx — Horizontal Gradient Blue = Negative · White = Zero · Bright Blue = Positive
Gy — Vertical Gradient Amber = Negative · White = Zero · Bright Amber = Positive
Legend:
Inspected 3×3 Neighborhood
Central Pixel
Edge (Forced to 0)
Hover over an inner magnitude pixel to see the Gx and Gy decomposition.
Figure 3.33: EP03_08 Simulator: Sobel Gradient (Gx and Gy)
%%writefile EP03_08.py
# Python code
Overwriting EP03_08.py
TestSuite("EP03_08.py").run()
✔️ EP03_08.cases already exists in casos/
📋 5 case(s) loaded from casos/EP03_08.cases

🔍 Testing Python: EP03_08.py
⚠️ EP03_08.py: Empty file (fewer than 3 lines). Tests skipped.