How to detect corners using the Harris Corner method in OpenCV

This recipe helps you detect corners using the Harris Corner method in OpenCV

Recipe Objective: How to detect corners using the Harris Corner method in OpenCV?

In this recipe, we are going to understand how to detect corners using the Harris Corner method.

Step 1: Import the libraries and read the image.

Let us first import the necessary libraries and read the image. The image that we are using here is the one shown below. Let us also convert the image to grayscale for later use.

Input Image

import numpy as np
import cv2
image = cv2.imread('chess.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Step 2: Harris Corner detection method

This method, of course, involves a lot of mathematical processes running behind the hood. But trying to explain everything might be a little overwhelming. Hence, the basic idea of how it works is described in the following three steps.

  1. A fixed-size window is made to slide throughout the image and find the window that produces huge intensity variation when moved in both X and Y directions.
  2. For each such window found, a score R is computed.
  3. The necessary corners are then selected by applying a threshold to this score. Generally, when R is small, the region is considered a flat region. When R is less than 0, the region is considered an edge, and R is large, the region is considered a corner.

Harris corner detection can be implemented using the cv2.cornerHarris() method, which takes the following arguments.

  • src: The input image
  • blockSize: The neighborhood window size
  • ksize: The aperture for Sobel operator (This value is helpful for the calculation of the R score)
  • k: The harris detector free parameter

The cv2.cornerHarris() method takes the input image in np.float32 format. So let us convert our input image to that type.

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

Step 3: Dilate the output and set a threshold.

Let us now dilate the output that we received from the cv2.cornerHarris() method using the cv2.dilate() function. The dilated image is then reverted to its original form using the optimal threshold value. Here we consider the product of 0.1 and the maximum value of the dilated image as the optimum threshold. The points that pass the threshold are marked in red to indicate that they are the detected corners.

dst = cv2.dilate(dst, None)
image[dst > 0.01 * dst.max()] = [0, 0, 255]

Step 4: Display the output

Let us now display the output using cv2.imshow() function.

cv2.imshow('Detected corners', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Harris corner

Download Materials

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Build a CNN Model with PyTorch for Image Classification
In this deep learning project, you will learn how to build an Image Classification Model using PyTorch CNN

Detectron2 Object Detection and Segmentation Example Python
Object Detection using Detectron2 - Build a Dectectron2 model to detect the zones and inhibitions in antibiogram images.

Image Segmentation using Mask R-CNN with Tensorflow
In this Deep Learning Project on Image Segmentation Python, you will learn how to implement the Mask R-CNN model for early fire detection.

Build Regression Models in Python for House Price Prediction
In this Machine Learning Regression project, you will build and evaluate various regression models in Python for house price prediction.

NLP Project for Beginners on Text Processing and Classification
This Project Explains the Basic Text Preprocessing and How to Build a Classification Model in Python

Learn to Build an End-to-End Machine Learning Pipeline - Part 2
In this Machine Learning Project, you will learn how to build an end-to-end machine learning pipeline for predicting truck delays, incorporating Hopsworks' feature store and Weights and Biases for model experimentation.

Forecasting Business KPI's with Tensorflow and Python
In this machine learning project, you will use the video clip of an IPL match played between CSK and RCB to forecast key performance indicators like the number of appearances of a brand logo, the frames, and the shortest and longest area percentage in the video.

Word2Vec and FastText Word Embedding with Gensim in Python
In this NLP Project, you will learn how to use the popular topic modelling library Gensim for implementing two state-of-the-art word embedding methods Word2Vec and FastText models.

MLOps Project to Build Search Relevancy Algorithm with SBERT
In this MLOps SBERT project you will learn to build and deploy an accurate and scalable search algorithm on AWS using SBERT and ANNOY to enhance search relevancy in news articles.

Insurance Pricing Forecast Using XGBoost Regressor
In this project, we are going to talk about insurance forecast by using linear and xgboost regression techniques.