OpenCV  3.1.0-dev
Open Source Computer Vision
Harris Corner Detection

Goal

In this chapter,

Theory

In last chapter, we saw that corners are regions in the image with large variation in intensity in all the directions. One early attempt to find these corners was done by Chris Harris & Mike Stephens in their paper A Combined Corner and Edge Detector in 1988, so now it is called Harris Corner Detector. He took this simple idea to a mathematical form. It basically finds the difference in intensity for a displacement of \((u,v)\) in all directions. This is expressed as below:

\[E(u,v) = \sum_{x,y} \underbrace{w(x,y)}_\text{window function} \, [\underbrace{I(x+u,y+v)}_\text{shifted intensity}-\underbrace{I(x,y)}_\text{intensity}]^2\]

Window function is either a rectangular window or gaussian window which gives weights to pixels underneath.

We have to maximize this function \(E(u,v)\) for corner detection. That means, we have to maximize the second term. Applying Taylor Expansion to above equation and using some mathematical steps (please refer any standard text books you like for full derivation), we get the final equation as:

\[E(u,v) \approx \begin{bmatrix} u & v \end{bmatrix} M \begin{bmatrix} u \\ v \end{bmatrix}\]

where

\[M = \sum_{x,y} w(x,y) \begin{bmatrix}I_x I_x & I_x I_y \\ I_x I_y & I_y I_y \end{bmatrix}\]

Here, \(I_x\) and \(I_y\) are image derivatives in x and y directions respectively. (Can be easily found out using cv2.Sobel()).

Then comes the main part. After this, they created a score, basically an equation, which will determine if a window can contain a corner or not.

\[R = det(M) - k(trace(M))^2\]

where

So the values of these eigen values decide whether a region is corner, edge or flat.

It can be represented in a nice picture as follows:

harris_region.jpg
image

So the result of Harris Corner Detection is a grayscale image with these scores. Thresholding for a suitable give you the corners in the image. We will do it with a simple image.

Harris Corner Detector in OpenCV

OpenCV has the function cv2.cornerHarris() for this purpose. Its arguments are :

See the example below:

1 import cv2
2 import numpy as np
3 
4 filename = 'chessboard.png'
5 img = cv2.imread(filename)
6 gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
7 
8 gray = np.float32(gray)
9 dst = cv2.cornerHarris(gray,2,3,0.04)
10 
11 #result is dilated for marking the corners, not important
12 dst = cv2.dilate(dst,None)
13 
14 # Threshold for an optimal value, it may vary depending on the image.
15 img[dst>0.01*dst.max()]=[0,0,255]
16 
17 cv2.imshow('dst',img)
18 if cv2.waitKey(0) & 0xff == 27:
19  cv2.destroyAllWindows()

Below are the three results:

harris_result.jpg
image

Corner with SubPixel Accuracy

Sometimes, you may need to find the corners with maximum accuracy. OpenCV comes with a function cv2.cornerSubPix() which further refines the corners detected with sub-pixel accuracy. Below is an example. As usual, we need to find the harris corners first. Then we pass the centroids of these corners (There may be a bunch of pixels at a corner, we take their centroid) to refine them. Harris corners are marked in red pixels and refined corners are marked in green pixels. For this function, we have to define the criteria when to stop the iteration. We stop it after a specified number of iteration or a certain accuracy is achieved, whichever occurs first. We also need to define the size of neighbourhood it would search for corners.

1 import cv2
2 import numpy as np
3 
4 filename = 'chessboard2.jpg'
5 img = cv2.imread(filename)
6 gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
7 
8 # find Harris corners
9 gray = np.float32(gray)
10 dst = cv2.cornerHarris(gray,2,3,0.04)
11 dst = cv2.dilate(dst,None)
12 ret, dst = cv2.threshold(dst,0.01*dst.max(),255,0)
13 dst = np.uint8(dst)
14 
15 # find centroids
16 ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
17 
18 # define the criteria to stop and refine the corners
19 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
20 corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),(-1,-1),criteria)
21 
22 # Now draw them
23 res = np.hstack((centroids,corners))
24 res = np.int0(res)
25 img[res[:,1],res[:,0]]=[0,0,255]
26 img[res[:,3],res[:,2]] = [0,255,0]
27 
28 cv2.imwrite('subpixel5.png',img)

Below is the result, where some important locations are shown in zoomed window to visualize:

subpixel3.png
image

Additional Resources

Exercises