Harris Corner Detection

Prerequisites

Don’t begin this exercise until you’re familiar with the basic image processing techniques (morphological transformations etc.) . Its easy to learn and apply, but you’ll run into trouble if you want to extend yourself after tutorial.

Introducing the function

The Harris corner detector is -you won’t believe it- a function in OpenCV that allows you to detect corners in images. Its one of few methods that allow you to detect corners, and this is the gist of this method:

Corners are essentially regions of an image with considerable variations of intensity (assuming a monochrome image) in all directions. Take the picture below for instance, in every direction, there’s a different color. This is how the Harris corner detector finds corners: By taking the values of the pixels around a given pixel, it is able to determine whether or not the pixel is associated with a corner or not.

Corner detector.png

Applying the function

The code will be split up into 2 parts; a function I made for simplicity’s sake, followed by the Harris corner detector function.

import cv2
import numpy as np
window = 1
def imshow(img):
    global window
    name = "Window %d" %(window)
    window +=1
    cv2.imshow(name, img)

This first bit of the function really has nothing to do with the Harris Corner detector function itself. After doing a load of projects, you’ll realize how annoying it is to constantly specify a name for each of your windows with the cv2.imshow() function. This is especially a pain whilst debugging, so here’s a function called imshow() that simplifies this process, by taking an img as a parameter.

#insert image location in "loc"
loc = "C:\Users\user pc\Desktop\PPictures\chessboard.png"
img = cv2.imread(loc)
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
grey = np.float32(grey)

#use the harris corner function to locate corners
new = cv2.cornerHarris(grey, 5, 3, 0.04)

#Optimal value thersholding may vary from image to imag
img[new>0.01*new.max()]=[255,102,255]

#show the image
imshow(img)
cv2.imwrite('C:\Users\user pc\Desktop\PPictures\chessboardman.png',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

OpenCV allows you to implement the corner detection algorithm in one neat, simple function, cv2.cornerHarris(img, blocksize, ksize, k). This function takes the following parameters:

  • img – Float 32 input image
  • blocksize – Determines the size of the neighborhood of surrounding pixels considered
  • ksize – Aperture parameter for Sobel (the x and y derivatives are found using the sobel function)
  • k – Harris detector free parameter

chessboardcrossed

The above images are the results of the cv2.cornerHarris() function. On these still images, it works pretty well!

 

Leave a comment