Detecting edges

Edge detection is one of the most popular techniques in Computer Vision. It is used as a preprocessing step in many applications. Let's look at how to use different edge detectors to detect edges in the input image.

How to do it…

  1. Create a new Python file, and import the following packages:
    import sys
    
    import cv2
    import numpy as np 
  2. Load the input image. We will use chair.jpg:
    # Load the input image -- 'chair.jpg'
    # Convert it to grayscale 
    input_file = sys.argv[1]
    img = cv2.imread(input_file, cv2.IMREAD_GRAYSCALE)
  3. Extract the height and width of the image:
    h, w = img.shape
  4. Sobel filter is a type of edge detector that uses a 3x3 kernel to detect horizontal and vertical edges separately. You can learn more about it at http://www.tutorialspoint.com/dip/sobel_operator.htm. Let's start with the horizontal detector:
    sobel_horizontal = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)
  5. Run the vertical Sobel detector:
    sobel_vertical = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5)
  6. Laplacian edge detector detects edges in both the directions. You can learn more about it at http://homepages.inf.ed.ac.uk/rbf/HIPR2/log.htm. We use it as follows:
    laplacian = cv2.Laplacian(img, cv2.CV_64F)
  7. Even though Laplacian addresses the shortcomings of Sobel, the output is still very noisy. Canny edge detector outperforms all of them because of the way it treats the problem. It is a multistage process, and it uses hysteresis to come up with clean edges. You can learn more about it at http://homepages.inf.ed.ac.uk/rbf/HIPR2/canny.htm:
    canny = cv2.Canny(img, 50, 240)
  8. Display all the output images:
    cv2.imshow('Original', img)
    cv2.imshow('Sobel horizontal', sobel_horizontal)
    cv2.imshow('Sobel vertical', sobel_vertical)
    cv2.imshow('Laplacian', laplacian)
    cv2.imshow('Canny', canny)
    
    cv2.waitKey()
  9. The full code is given in the edge_detector.py file that is already provided to you. The original input image looks like the following:
    How to do it…
  10. Here is the horizontal Sobel edge detector output. Note how the detected lines tend to be vertical. This is due the fact that it's a horizontal edge detector, and it tends to detect changes in this direction:
    How to do it…
  11. The vertical Sobel edge detector output looks like the following image:
    How to do it…
  12. Here is the Laplacian edge detector output:
    How to do it…
  13. Canny edge detector detects all the edges nicely, as shown in the following image:
    How to do it…
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.29.195