Python OpenCV: Implement Harris Corner Detector Using cv2.cornerHarris()

In this tutorial, we will create a harris corner detector to detect an image using cv2.cornerHarris() in python opencv.

Python OpenCV - Implement Harris Corner Detector Using cv2.cornerHarris() for Beginners

1.Import library

import cv2
import numpy as np
from matplotlib import pyplot as plt

2.Open an image as grayscale

image_bgr = cv2.imread('images/plane_256x256.jpg')
image_gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
image_gray = np.float32(image_gray)

3.Set corner detector parameters

block_size = 2
aperture = 29
free_parameter = 0.04

4.Create  harris corner detector using cv2.cornerHarris()

detector_responses = cv2.cornerHarris(image_gray, block_size, aperture, free_parameter)

5.Mark corners

# Large corner markers
detector_responses = cv2.dilate(detector_responses, None)

# Only keep detector responses greater than threshold, mark as white
threshold = 0.02
image_bgr[detector_responses > threshold * detector_responses.max()] = [255,255,255]

7.Display image

image_gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)

# Show image
plt.imshow(image_gray, cmap='gray'), plt.axis("off")
plt.show()

Run this code, you may see this image:

Python OpenCV: Implement Harris Corner Detector Using cv2.cornerHarris()