PIXELBANKv9.1.0
Menu

Sobel Edge Magnitude and Direction

Given a 2D grayscale image, compute both the X and Y Sobel gradients, then derive the gradient magnitude and direction at each pixel.

The Sobel kernels are: Gx=[−101−202−101],Gy=[−1−2−1000121]G_x = \begin{bmatrix} -1 & 0 & 1 \\ -2 & 0 & 2 \\ -1 & 0 & 1 \end{bmatrix}, \quad G_y = \begin{bmatrix} -1 & -2 & -1 \\ 0 & 0 & 0 \\ 1 & 2 & 1 \end{bmatrix}

For each valid position compute:

  • Magnitude: M=Gx2+Gy2M = \sqrt{G_x^2 + G_y^2}
  • Direction: θ=atan2(Gy,Gx)\theta = \text{atan2}(G_y, G_x) in degrees

Return a tuple (magnitude_matrix, direction_matrix), both rounded to 2 decimal places.

Example:

Input:
image = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output:
([[25.3]], [[71.57]])
Reasoning:
  • The given image is a 3x3 matrix, but since the Sobel kernels are 3x3, we can only apply them to the center pixel to get valid results, which is why the output matrices are 1x1.
  • We calculate the X and Y Sobel gradients for the center pixel (5) using the given kernels: Gx=(−1â‹…4)+(0â‹…5)+(1â‹…6)=2G_x = (-1 \cdot 4) + (0 \cdot 5) + (1 \cdot 6) = 2 and Gy=(−1â‹…4)+(−2â‹…5)+(1â‹…6)=−7G_y = (-1 \cdot 4) + (-2 \cdot 5) + (1 \cdot 6) = -7 (considering only the corresponding elements of the kernel and the image that overlap with the center pixel).
  • Then, we compute the magnitude M=Gx2+Gy2=22+(−7)2=53≈25.3M = \sqrt{G_x^2 + G_y^2} = \sqrt{2^2 + (-7)^2} = \sqrt{53} \approx 25.3 and direction θ=atan2(−7,2)≈71.57∘\theta = \text{atan2}(-7, 2) \approx 71.57^\circ.
  • The final output is a tuple containing the magnitude and direction matrices, both rounded to 2 decimal places: ([[25.3]],[[71.57]])([[25.3]], [[71.57]]).

Constraints:

  • Input image is a 2D list (at least 3x3)
  • Use math.sqrt and math.atan2, math.degrees
  • Return tuple of two 2D lists, each rounded to 2 decimal places
solution.py

Test Results

0/0
Run code to see test results.
Sobel Edge Magnitude and Direction - Medium | PixelBank