Ririe Sakamaki
Ririe Sakamaki

Reputation: 13

How to count number of features detected through Harris Corner Detection?

I am still new to OpenCV and Python. I am using the following Harris Corner Detection code. As you can see, the result is also given below. Now, how do I count the number of features detected as those red dots? Please note that I am a beginner so you might need to elaborate the answer.

import cv2
import numpy as np

filename = 'image.jpg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)

dst = cv2.dilate(dst,None)

img[dst>0.01*dst.max()]=[0,0,255]

cv2.imshow('dst',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

This is the result

Upvotes: 0

Views: 1486

Answers (1)

rayryeng
rayryeng

Reputation: 104464

This line finds any location in the Harris corner response map that exceeds the detection threshold and sets those locations to red:

img[dst>0.01*dst.max()]=[0,0,255]

What is returned from the Harris corner detector function is a response map that gives you the "probability" that a particular pixel is a corner point. Therefore, if we thresholded this response map it would give us the locations of where corners are located in the image. This thresholded map is thus a binary mask, which is being used to index into the input image that helps you delineate where these locations are. Because it's a binary mask, you can just calculate the sum of this mask to tell you how many corner points there are:

num_corners = np.sum(dst > 0.01 * dst.max())

Take note that you should do this before the dilation step as the dilation step is primarily used for visualisation so you can see the corners better. Therefore, run the above code right after you run the Harris corner detector:

dst = cv2.cornerHarris(gray,2,3,0.04)
num_corners = np.sum(dst > 0.01 * dst.max())

Upvotes: 4

Related Questions