Image Edge Detection in Python using OpenCV: Step-by-step — CODEFATHER
--
In this tutorial, we will implement image edge detection in Python. Edge detection is a very common image processing technique.
To implement image edge detection in Python you can use the OpenCV library. One of the edge detection algorithms provided by OpenCV is the Canny algorithm.
We will go through the process of reading an image with OpenCV, converting it to grayscale, and generating a new image where edges have been detected.
Let’s see this in practice!
Which Python Library Can Be Used For Image Processing?
The OpenCV library allows performing image processing in Python. OpenCV stands for Open Source Computer Vision.
To install the OpenCV library you can use the following pip command:
pip install opencv-python
Then you can test that the OpenCV library is available in your Python distribution by using the following import statement in the Python shell:
>>> import cv2
Make sure Python doesn’t throw any errors.
How Do You Detect Edges in Images Using OpenCV and Python?
With the OpenCV library, you can read an image from a file using the imread() method. After that, you can apply any edge detection algorithm you want.
In this tutorial, we will try to detect edges for the Mona Lisa painting by Leonardo (download the JPEG file here).
After downloading the JPEG file rename it to mona_lisa.jpeg, then read it using OpenCV’s imread() function.
We will convert the image to grayscale to simplify the edge detection process considering that a grayscale image requires less computation than a color image.
import cv2 as cv
image_path = 'mona_lisa.jpeg'
image = cv.imread(image_path, cv.IMREAD_GRAYSCALE)
print(type(image))
To detect edges in this image you can apply the Canny edge detection algorithm implemented in OpenCV using the function cv2.Canny().