PIXELBANKv9.1.0
Menu

Gradient Magnitude and Direction

Implement a function to compute the gradient magnitude and direction from given horizontal and vertical gradient components, a crucial step in edge detection algorithms. This process is essential in image processing to identify and analyze the boundaries of objects within an image.

The gradient of an image is a measure of how the intensity of the image changes in different directions, which can be represented by its horizontal (GxG_x) and vertical (GyG_y) components. The magnitude of the gradient indicates the strength of the edge, while the direction indicates the orientation of the edge.

Here are the steps to compute the gradient magnitude and direction:

  1. Compute the magnitude using the given GxG_x and GyG_y components.
  2. Calculate the direction using the arctan2 function.
magnitude=Gx2+Gy2\text{magnitude} = \sqrt{G_x^2 + G_y^2} direction=arctan⁑2(Gy,Gx)\text{direction} = \arctan2(G_y, G_x)

This technique is widely used in computer vision applications, such as object recognition and image segmentation.

Example:

Input:
image = [[100, 100, 100],
        [100, 150, 100],
        [100, 100, 100]]
Output:
Gx = [[0, 0, 0],
     [50, 0, -50],
     [0, 0, 0]]
Gy = [[0, 50, 0],
     [0, 0, 0],
     [0, -50, 0]]
Reasoning:

Image gradient formulas (central difference):

Gx[i,j]=I[i,j+1]βˆ’I[i,jβˆ’1]2G_x[i,j] = \frac{I[i,j+1] - I[i,j-1]}{2} Gy[i,j]=I[i+1,j]βˆ’I[iβˆ’1,j]2G_y[i,j] = \frac{I[i+1,j] - I[i-1,j]}{2}

Computing GxG_x (horizontal gradient) at position (1,1)(1,1): Gx=I[1,2]βˆ’I[1,0]2=100βˆ’1002=0G_x = \frac{I[1,2] - I[1,0]}{2} = \frac{100 - 100}{2} = 0

Computing GyG_y (vertical gradient) at position (1,1)(1,1): Gy=I[2,1]βˆ’I[0,1]2=100βˆ’1002=0G_y = \frac{I[2,1] - I[0,1]}{2} = \frac{100 - 100}{2} = 0

At position (1,0)(1,0) - left edge of center row: Gx=I[1,1]βˆ’I[1,βˆ’1]2=150βˆ’1002=25G_x = \frac{I[1,1] - I[1,-1]}{2} = \frac{150 - 100}{2} = 25 (using boundary handling)

Gradient magnitude and direction: βˆ£βˆ‡I∣=Gx2+Gy2|\nabla I| = \sqrt{G_x^2 + G_y^2} ΞΈ=arctan⁑2(Gy,Gx)\theta = \arctan2(G_y, G_x)

For the bright center pixel (150)(150), gradients point outward in all directions, indicating edges around the bright spot.

Constraints:

  • gx and gy are gradient images (2D arrays) of the same size
  • Return tuple of (magnitude, direction) where both are 2D arrays
  • Magnitude rounded to 2 decimal places
  • Direction in degrees [0, 360), rounded to 2 decimal places
solution.py

Test Results

0/0
Run code to see test results.
Gradient Magnitude and Direction - Easy | PixelBank