Detecting Corners of Shapes in Python OpenCV

FeaImg DetectCorners

Hey Folks! In this tutorial, we’ll teach you how to use Python’s OpenCV package to identify corners in an image. Algorithms in OpenCV are available for detecting corners in images.

Introduction to Corner Detection

A corner is a location with two dominating and opposing edge orientations in its local vicinity. In other terms, a corner may be defined as the intersection of two edges, where an edge represents a sharp change in picture brightness.

CornerDetect Demo
CornerDetect Demo

Corners are the most essential aspects of the image, and they are sometimes referred to as interest points since they are insensitive to translation, rotation, and illumination.

Implementing Corner Detection in Python

Step 1: Importing all the necessary Modules/Libraries

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

Step 2: Loading the Image and converting into a gray image

The next step involves loading the image using the cv2.imread function which will take the path of the image that needs to be loaded. To make the processing easier, we will convert the image into a gray image using the cv2.cvtColor function.

We will display the image with the help of the plt.imshow method of the matplotlib library.

img = cv2.imread('sample_shape1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Sample Shape CornerDetection
Sample Shape CornerDetection

Step 3: Detecting Corners of the Image

The Shi-Tomasi approach is used by the cv2.goodFeaturesToTrack() function to determine the N strongest corners in an image.

corners = cv2.goodFeaturesToTrack(gray, 27, 0.01, 10)
corners = np.int0(corners)

Step 4: Plotting the corner points

At each corner, we aim to plot a simple red dot using the code snippet mentioned below. And in the final section plot the final corner detected image.

for i in corners:
	x, y = i.ravel(), (x, y), 4, 200, -1)

Detect Cornes Output 1
Detect Cornes Output 1

Sample Output 2

Detect Cornes Output 2
Detect Cornes Output 2


Congratulations! You just learned how to build a python program to detect corners of an image using OpenCV. Hope you enjoyed it! 😇

Liked the tutorial? In any case, I would recommend you to have a look at the tutorials mentioned below:

  1. ORB Feature Detection in Python
  2. Color Detection using Python – Beginner’s Reference
  3. Python: Detecting Contours
  4. Edge Detection in Images using Python

Thank you for taking your time out! Hope you learned something new!! 😄