Hello, Readers, I hope you liked my previous posts on Face detection with OpenCV. I used python to show you the code. Here I am going to discuss Edge detection in OpenCV. Also, I will show you how to implement Edge detection in OpenCV using python.
Ready? Let’s get started.
First of all, let me list the basics.
Image processing basics
What is an image? Let’s find out. Save below code as ‘image.py’ and run it as ‘python image.py.’
import cv2 img = cv2.imread('photo.jpg') img_graysacle = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) print img #print img_graysacle
Notice that the output is a 3D array. Here our image that we are printing is a colored image. Now, what if it was grayscale? Let’s find out.
Hey, now we are getting a 2D array as our output of the print statement. So we got our answer. An image having all the colors, or an RGB image is 3D. And a grayscale, indexed or binary image is a 2D one. Here by 2D and 3D I mean the image’s representation.
The color of each pixel in a colored RGB picture depends on the combination of the red, green and blue color intensities.
So, now we know how to represent images in image processing. Let’s see what an edge is.
See the image below.
It looks like a face, more specifically, a female face. But how do we get to that inference?
Note that details like color, description, and depth are missing, but we could still tell.
It is the edges. We recognized this simple image using its edges.
Edges and Edge detection techniques
In simple terms, edges are those places in a picture where the pixel intensity changes suddenly. They are just some connected pixels that lie on the boundary between two regions with different pixel intensities.
For our eyes, it is so easy to identify edges. But how can we make the computer detect edges in a picture? Let’s understand.
In principle, we first calculate the first derivative of the image. Then we look for those points which are peaks, and have values larger than their neighboring points Set of those connected ‘extrema’ points is an edge.
But any image does contain at least some noise. We have to first of all filter out any noise. OpenCV offers a variety of filters for denoising.
We choose an appropriate filter depending upon the nature of the noise. We will make the use of Gaussian blur function as an example in our Edge detection with OpenCV example.
OpenCV has a lot of inbuilt functions to detect edges, corners, circles, etc. in an image. You can see some of them here: OpenCV feature detection. Now let us see how to perform Edge detection in OpenCV. I will use the Python binding of OpenCV. You can follow along or download the code from the link available at the end of the post.
Sobel Filter for edge detection in OpenCV
import cv2 import numpy as np img = cv2.imread('image.jpg',cv2.IMREAD_GRAYSCALE) rows,cols = img.shape sobel_horizontal = cv2.Sobel(img,cv2.CV_64F,1,0,ksize = 5) sobel_vertical = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5) cv2.imshow('Original',img) cv2.imshow('Sobel Horizontal Filter',sobel_horizontal) cv2.imshow('Sobel Vertical Filter',sobel_vertical) cv2.waitKey(0)
See the results.
Here is the original image converted to grayscale on line number 4.
And here are the results for each filter.
As you can see, the result is not much impressive. The filters are calculating the gradient change from either horizontal or vertical side. Also, noise is still causing problems.
Laplacian filter for edge detection
I will try Laplacian filter now. It checks for gradient change in both directions. Let us see how that works. Use the following code.
import cv2 import numpy as np img = cv2.imread('image.jpg',cv2.IMREAD_GRAYSCALE) rows,cols = img.shape denoised = cv2.GaussianBlur(img,(5,5),0) filter = cv2.Laplacian(denoised,cv2.CV_64F) cv2.imshow('Original',img) cv2.imshow('Laplacian Filter',filter) cv2.waitKey(0)
I have denoised the image using the Gaussian blur technique. Also, I have applied a Laplacian filter to the picture.
And here is the result.
Note now the edges are much distinct. But there is still some noise in the output. Laplacian filter applies the gradient check well on the denoised image. Impressed yet? Well, I have something more to show you.
Canny Edge detector for edge detection in OpenCV
I tried the Canny edge detector operator. It uses a multi-stage algorithm. The Canny algorithm has a low error rate hence the accuracy is great. Also, it marks the edges in the image only once. So, noise does not result in false edges.
Here is the code. I have explained it below.
import cv2 import numpy as np img = cv2.imread('image.jpg',cv2.IMREAD_GRAYSCALE) filter = cv2.Canny(img,100,200) cv2.imshow('Original',img) cv2.imshow('Laplacian Filter',filter) cv2.waitKey(0)
I have not used the Gaussian blur function before passing the image through the Canny function. So Canny edge detector has to filter out the noise implicitly. You can read more features of the Canny edge detector function in OpenCV here.
Let me show you the result.
Edge detection in OpenCV using videos in real time
How awesome would it be if we could find edges in videos? I am going to show you how we can detect edges in OpenCV of real time videos. I will be using the webcam input. So, the video feed will pass through the canny edge detector, and we will see an output feed on the screen.
Make sure your web camera is working. Otherwise, you can just pass any video file from your disk to the VideoCapture() function’s parameter. And here is the code.
from transform import four_point_transform import numpy as np import argparse import cv2 cap = cv2.VideoCapture(0) while(1): ret, frame = cap.read() gray_vid = cv2.cvtColor(frame, cv2.IMREAD_GRAYSCALE) cv2.imshow('Original',frame) edged_frame = cv2.Canny(frame,100,200) cv2.imshow('Edges',edged_frame) k= cv2.waitKey(5)&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;0xFF if k==27: break cap.release() cv2.destroyAllWindows()
First of all, I am reading all the frames through my webcam. Each frame is converted to grayscale. I am using the Canny edge detector in this example. Finally, I am showing both the frames as output.
If you need to download all codes of this post, I have added them to my Github repository. Here is the link. Edge detection algorithms comparison in OpenCV Python
I hope you liked this simple tutorial on Edge detection with OpenCV. Please leave your comments and suggestions. If you have any questions, drop them in the comments box below. You can check out my Oracle database tutorial series. Also, do subscribe to this website. More tutorials are coming soon.