OpenCV allows you to manipulate images and videos. There are many functions in it that perform it. Suppose you want to implement OpenCV edge detection. Then how you can do so. The answer is here. In this entire tutorial, you will know how to detect edges of an image using the cv2 canny method. All tasks will be implemented step by step.
Steps for OpenCV edge detection through cv2 Canny method
Before going through the steps in detail below is the image file I will implement OpenCV edge detection.
Step 1: Import the necessary library
In this tutorial, I am using the OpenCV package only. Make sure you have installed the OpenCV python library. Then import it using the import statement.
Step 2: Read the Image File
The next step is to read the image file. Any image in OpenCV can be read using the cv2.imread() method. Execute the code below to read the image.
img = cv2.imread("dove.jpg")
Step 3: Implement the cv2 Canny method.
Now, after reading the image, let’s detect the image using the cv2.Canny() method. Generally, The Canny() method accepts three arguments. The first argument is your input image. The second and third arguments are aperture_size and L2gradient also know as threshold values. Threshold values allow you to classify the pixel intensities in the image.
Let’s use the cv2.Canny() method on the image.
edges = cv2.Canny(img,100,70)
You can see the I am using 100 and 70 as the aperture size and L2 gradient.
Step 4: Show and Compare the Image
After implementing all the above let’s show and compare the image. In OpenCV, you can show the image using the cv2.imshow() method. After that, if you are using cv2 on windows then you have to use cv2.waitKey(0) to display the image indefinitely until you press the keyboard.
Below is the full code for this tutorial and its output.
import cv2 img = cv2.imread("dove.jpg") cv2.imshow("Original Image",img) edges = cv2.Canny(img,100,70) cv2.imshow("Canny Image",edges) cv2.waitKey(0) cv2.destroyAllWindows()
Hurray! You have successfully detected the edge of a dove bird image. In the same way, you can detect edges for any image you want. Just you have to keep varying the threshold values to detect the best edges on the image.
These are steps to implement cv2.Canny() method and detect edges using it. Hope you have liked this tutorial. If you have any queries regarding this post then you can contact us. We are always ready to help you.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.