v9.1.1
Menu

Implement Prewitt Edge Detector

hardFREEBrief HistoryEdge DetectionCV: Introduction to Computer Vision

Implement the Prewitt edge detector, one of the earliest edge detection methods (1970).

The Prewitt operator uses two 3×3 kernels to compute horizontal and vertical gradients:

Gx=(−101−101−101)∗I,Gy=(−1−1−1000111)∗IG_x = \begin{pmatrix} -1 & 0 & 1 \\ -1 & 0 & 1 \\ -1 & 0 & 1 \end{pmatrix} * I, \quad G_y = \begin{pmatrix} -1 & -1 & -1 \\ 0 & 0 & 0 \\ 1 & 1 & 1 \end{pmatrix} * I

The edge magnitude and direction are: G=Gx2+Gy2,θ=arctan⁡(GyGx)G = \sqrt{G_x^2 + G_y^2}, \quad \theta = \arctan\left(\frac{G_y}{G_x}\right)

Here ∗* means centring the kernel on each pixel and summing the element-wise products, without flipping the kernel (so Gx>0G_x > 0 when the column to the right is brighter than the column to the left, and Gy>0G_y > 0 when the row below is brighter than the row above). Pixels outside the image count as 0.

The direction θ\theta is the full-circle angle of the vector (Gx,Gy)(G_x, G_y): the signs of both components decide the quadrant, so e.g. Gx=Gy=−255G_x = G_y = -255 gives 225°225°, not 45°45°. A pixel with Gx=Gy=0G_x = G_y = 0 gets direction 0°0°.

Return both the magnitude map and the edge direction map (in degrees, in [0,360)[0, 360)).

Example

Input
image = [[0, 0, 0],
         [0, 255, 0],
         [0, 0, 0]]
Output
{'magnitude': [[360.62, 255.0, 360.62], [255.0, 0.0, 255.0], [360.62, 255.0, 360.62]], 'direction': [[45.0, 90.0, 135.0], [0.0, 0.0, 180.0], [315.0, 270.0, 225.0]]}
Reasoning
  • Input: image is a 3×33 \times 3 grayscale grid, all zeros except one bright pixel of 255 at the centre; everything outside the border counts as 0.
  • Centre (1,1): its window holds 255 only in the middle cell, where both kernels are 0, so Gx=Gy=0G_x = G_y = 0: magnitude 0.0, and the undefined angle is reported as 0.0.
  • Left neighbour (1,0): the 255 lands in its window's right column, middle row: Gx=(+1)(255)=255G_x = (+1)(255) = 255, Gy=0G_y = 0, so G=255G = 255 and θ=0°\theta = 0°.
  • Top-left corner (0,0): the 255 is in the bottom-right window cell, weighted +1+1 by both kernels: G=2552+2552=2552≈360.62G = \sqrt{255^2 + 255^2} = 255\sqrt{2} \approx 360.62, θ=45°\theta = 45°.
  • Bottom-right corner (2,2): both components are −255-255, the third quadrant, so θ=225°\theta = 225°, not the 45°45° that arctan⁡(Gy/Gx)=arctan⁡(1)\arctan(G_y/G_x) = \arctan(1) alone would give.
  • Notice the ring of directions 0°,45°,…,315°0°, 45°, \dots, 315°: every neighbour's gradient points toward the bright pixel (rows count downward).

Constraints

  • image: 2D grayscale array
  • Return: Dict with 'magnitude' and 'direction' arrays
  • Use zero-padding for borders
  • Direction in degrees [0, 360), rounded to 1 decimal
  • Magnitude rounded to 2 decimals

More from CV: Introduction to Computer Vision

solution.py

Test results

Sign in to run your code against the test cases.