How to implement Prewitt and Canny edge detection in cv2

Key takeaways:

  • Prewitt and Canny are edge detection techniques in image processing.

  • Prewitt uses convolution masks to detect edges and applies thresholding to highlight them.

  • Canny uses Gaussian blur, gradient calculation, and hysteresis for clearer, thinner edges.

  • Canny is more accurate but computationally heavier; Prewitt is faster but produces thicker edges.

Edge detection is a fundamental technique in image processing and computer vision, used to identify points where image intensity changes sharply. These points often represent object boundaries, allowing us to segment and analyze images more effectively.

Prewitt and Canny are two of the most commonly used methods for edge detection in images. Let's see how these methods work.

Prewitt edge detection

Prewitt edge detection is used to find both, horizontal and vertical edges in an image. In this method, edges are detected by comparing corresponding pixels and finding the difference between their intensity. Since we observe the change in intensity of pixels in an image, we can use differentiationDifferentiation is used to find the intensity gradient between neighboring pixels, which helps detect edges. to calculate it.

The Prewitt edge detection mask, also known as a kernel or derivative mask, is used to detect edges. Following are some common properties of masks used in most edge detection methods:

  • The maskmask is a small matrix used to convolve with an image in order to detect edges. should contain opposite signs (it should have both, positive and negative values).

  • The sum of the mask should be zero.

  • A higher weight in the values of the mask indicates a higher number of edge detection.

Following are the masks used in Prewitt edge detection for horizontal and vertical edge detection:

Horizontal and vertical masks
Horizontal and vertical masks

Implementing Prewitt edge detection in Python

We can find edges in an image using the Prewitt edge detection by following the steps given below:

  • First, we need to convert an image to grayscale if its not already. This allows us to simplify the edge detection process.

  • Apply convolutionIn convolution we slide our mask across the image to find the weighted sum of pixels that come under the mask. on the image using the horizontal and vertical masks.

  • Find the magnitude of the gradientThe gradient refers to the rate of change in intensity or color of the pixels in an image. by adding the results of the image after applying horizontal and vertical masks and finding its square root.

  • Finally, Apply thresholding to clear noise and find sharper edges. This step is optional.

Now, let’s see how we can implement Prewitt edge detection in Python in the widget given below:

import cv2
import numpy as np
def prewitt_edge_detection(image):
# Convert image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Create mask for the image
horizontal_mask = np.array([[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]])
vertical_mask = np.array([[-1, -1, -1],
[ 0, 0, 0],
[ 1, 1, 1]])
# Convolve image with the hortizontal and vertical masks
image_after_horizontal_mask = cv2.filter2D(gray_image, -1, horizontal_mask)
image_after_vertical_mask = cv2.filter2D(gray_image, -1, vertical_mask)
# Find the gradient magnitude
gradient_magnitude = np.sqrt(image_after_horizontal_mask**2 + image_after_vertical_mask**2).astype(np.uint8)
# Apply thresholding
_, edge_image = cv2.threshold(gradient_magnitude, 10, 255, cv2.THRESH_BINARY)
return edge_image
# Load an image
image = cv2.imread('Bot.png')
# Prewitt edge detection
edges = prewitt_edge_detection(image)
cv2.imwrite('output/img1.png', image) #original image
cv2.imwrite('output/img2.png', edges) #image after edge detection

In the code widget above, the first image is the sample image we provide to our edge detection function, and the second image displays the edges detected by our function. Let’s see what’s happening in this function in detail:

  • Line 6: We convert the image into a grayscale image.

  • Lines 9–15: We define our convolution masks.

  • Lines 19–20: We convolve the image using our masks by using the filter2D function available in the cv2 library.

    • gray_image is the source image that you want to filter.

    • -1 is the depth of the output image to use the same depth as the input image. It determines the data type of the output image.

    • Horizontal and vertical masks are the filters that are to be applied to the image.

  • Line 23: We find the gradient magnitude.

  • Line 26: We apply thresholding to the image.

    • gradient_magnitude: The image representing edge strength, calculated by combining horizontal and vertical gradients.

    • 10 (Threshold value): The cutoff for detecting edges; pixels with values greater than 10 are considered edges.

    • 255 (Maximum value): The value assigned to pixels above the threshold (representing edges).

    • cv2.THRESH_BINARY: A thresholding type that sets pixels greater than the threshold to 255 (white) and others to 0 (black).

Note: Click on the second image to see clear edge detection.

Canny edge detection

Canny edge detection is another method used to detect edges in an image. In this method, we perform the following steps to detect edges in an image:

  • The first step we perform in Canny edge detection is removing noise from the image using Gaussian blur to improve the quality of the image.

  • Then, find the gradient of the image using the Sobel operator. This operator provides us with the following masks to find horizontal and vertical edges in an image:

Horizontal and vertical masks
Horizontal and vertical masks
  • After finding the gradient value of all pixels in the image, we remove all gradients other than the local maxima.

  • We then use thresholding to remove all values less than or higher than a defined threshold.

  • Finally, we use hysteresisHysteresis is a process in edge detection where weak edges are removed unless they are connected to strong edges, helping to preserve true edges and reduce noise. to remove all weak edges that are not connected to any strong edges.

Implementing Canny edge detection in Python

Now that we know how the Canny edge detection method works, let’s implement it using the cv2 library available in Python.

import cv2
import numpy as np
def canny_edge_detection(image):
# Convert image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Use Gaussian Blur to remove noise from the image
gaussian_image = cv2.GaussianBlur(gray_image, (3, 3), 0)
# Perform Canny edge detection
edges = cv2.Canny(gaussian_image, 10, 250)
return edges
# Load an image
image = cv2.imread('Bot.png')
# Perform Canny edge detection
edges = canny_edge_detection(image)
cv2.imwrite('output/img1.png', image) #original image
cv2.imwrite('output/img2.png', edges) #image after edge detection

In the code widget above, the first image is the sample image we provide to our function, and the second image displays the edges detected by our Canny edge detection function. Let's see what's happening in this function in detail:

  • Line 6: We convert our image into a grayscale image.

  • Line 8: We use Gaussian Blur to remove noise from the image.

  • Line 12: We use the canny function available in the cv2 library to perform Canny edge detection on an image.

Note: Click on the second image to see clear edge detection.

Both Prewitt and Canny are algorithms that are used to detect edges in an image. You can select any one of these algorithms to find edges in an image based on your requirements. The Canny edge detection method is more advanced and detects thin and clear edges. On the other hand, Prewitt edge detection is computationally less expensive but may provide thick edges and is more sensitive to noise.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the difference between Canny Sobel and Prewitt edge detection?

Canny detects thinner, clearer edges using Gaussian blur, gradient calculation, and hysteresis, while Prewitt detects thicker edges with convolution masks. Sobel is similar to Prewitt but gives higher weight to vertical and horizontal gradients.


What is the Prewitt filter in OpenCV?

The Prewitt filter in OpenCV is used for edge detection by applying convolution with horizontal and vertical masks to detect image gradients.


Which is better Canny filter or Sobel filter?

Canny is better for detecting thinner and clearer edges, while Sobel is faster but less precise, detecting thicker edges.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved