Detecting corners using Harris corner detector in Python OpenCV


In OpenCV, the Harris corner detector is implemented using the function cv2.cornerHarris(). It accepts four arguments: img, blockSize, ksize, and k. Where img is the input image in grayscale and of float32 dtype, blockSize is the size of neighborhood considered for corner detection, ksize is Aperture parameter of Sobel derivative used and k is Harris detector free parameter in the equation.

Steps

To detect corners in an image using Harris corner detector, you could follow the steps given below

  • Import required libraries OpenCV and NumPy. Make sure you have already installed them.

  • Read the input image using cv2.imread() method. Specify the full path of the image. Convert the input image to grayscale image using cv2.cvtColor() metod. Convert the datatype of grayscale image to np.float32.

  • Apply cv2.cornerHarris() method on the grayscale image (float32). Pass suitable blockSize, ksize and k to the method as parameters.

  • Dilate the result for marking the corners and apply threshold for the optimal values.

  • Display the image with detected corners.

Let's see the examples to detect corners in an image using Harris Corner Detector.

Input Image

We use this image as an input file in the example below.


Example

This program demonstrates how to detect corners in an image using Harris corner detector algorithm −

# import required libraries import cv2 import numpy as np # load the input image img = cv2.imread('sudoku.jpg') # convert the input image into grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # modify the data type setting to 32-bit floating point gray = np.float32(gray) # apply the cv2.cornerHarris method to detect the corners corners = cv2.cornerHarris(gray, 2, 3, 0.05) #result is dilated for marking the corners corners = cv2.dilate(corners, None) # Threshold for an optimal value. img[corners > 0.01 * corners.max()]=[0, 0, 255] # the window showing output image with corners cv2.imshow('Image with Corners', img) cv2.waitKey(0) cv2.destroyAllWindows()

Output

When we execute the above code it will produce the following output window −


The above output image shows the corners detected using Harris corner detector. The corner points are shown in red color.

Updated on: 02-Dec-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements