DEV Community

Simarpreet Singh
Simarpreet Singh

Posted on • Originally published at Medium

Detecting Geometrical Shapes in an image using OpenCV

Well I was just exploring OpenCV library of python in this quarantine , and going through that, I came across term

Contours can be explained simply as a curve joining all the continuous points (along the boundary), having the same color or
intensity. The contours are a useful tool for shape analysis and object detection and recognition.And got to learn how we can use it to find geometrical shapes in an image.

Let’s start how it goes.

Approach : The approach we would use to detect the shape of a given polygon will be based on classifying the detected shape on the basis of a number of sides it has. For example, if the detected polynomial has 3 sides, then it could be considered as a triangle, if the polynomial has 4 sides then it could be classified as a square or a rectangle, and so on.
Let’s find how to do it
Importing libraries

import numpy as np
import cv2
Enter fullscreen mode Exit fullscreen mode

  1. Import image and convert to grayscale image.

3. Applying thresholding on image and then finding contours.

img = cv2.imread('shapes.PNG')
imgGry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

_, thrash = cv2.threshold(imgGry, 240 , 255, cv2.CHAIN_APPROX_NONE)
contours , _ = cv2.findContours(thrash, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
Enter fullscreen mode Exit fullscreen mode

ret ” collects a value, which according to OTSU method , is the best value for thresholding the image.

Thresholding is a technique in OpenCV, which is the assignment of pixel values in relation to the threshold value provided. In thresholding, each pixel value is compared with the threshold value. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a maximum value (generally 255).

and for “ thrash ”: its the threshold value of image

What is threshold value of an image?**

Threshold is some fixed value which draws a boundary line between two set of data. Binary (Bi-valued) Image means, only bi or two intensity values can be used to represent the whole image. In image processing generally, we say a image binary when, it consists only black and white pixels.

While using cv2.findContour(), we are receiving contours and hierarchy. Actually we got three arrays, first is the image, second is our contours, and one more output which we named as hierarchy.

Normally we use the cv2.findContours()** function to detect objects in an image, right ? Sometimes objects are in different locations. But in some cases, some shapes are inside other shapes, just like nested figures. In this case, we call the outer one as parent and inner one as child. This way, contours in an image has some relationship to each other. And we can specify how one contour is connected to each other, like, is it a child of some other contour, or is it a parent, etc. Representation of this relationship is called the Hierarchy.

Contours : Contours** can be explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition.

4 . Next step:**
a)Start the loop in range of contours and iterate through it .
b)Printing the polynomial name according to no. of contours together by using approxPolyDPfunction()**.

Short overview of functions used in this block:

approxPolyDP()** :This function calculates and approximates a polygonal curve with specified precision

approxPolyDP()** approximates a contour shape to another shape with less number of vertices depending upon the precision we specify. It is an implementation of Douglas-Peucker algorithm. Check the wikipedia page for algorithm and demonstration.

example of how approxpolyDp() works.

Alt Contour shape

drawContours(): Draws the contours outlines or filled color .
To draw the contours, _cv2.drawContours function is used. It can also be used to draw any shape provided you have its boundary points. Its first argument is source image, second argument is the contours which should be passed as a Python list, third argument is index of contours (useful when drawing individual contour. To draw all contours, pass -1) and remaining arguments are color, thickness etc._

BoundingRect() : It gives the boundary points of the rectangle.
putText() : It puts the text over the image.

5 . Show the image and close all windows**

and our Program runs successfully.
Image used :
Alt Image used

Output of code:
Alt output of code

Whole code available 👇:

Github link to this repo 👇:

GitHub logo simarpreetsingh-019 / openCV-Learning

Contains codes and Mini project made while learning OpenCV


This repository contains some programs that I learned while exploring the library : OpenCV using python

Articles Link

What is canny edge detection

Detecting Simple geometrical shapes in an image using OpenCV

Mini projects

  1. Pedestrian motion detection


  1. Detecting Geometrical shapes in an image


Thanks for reading! I hope you enjoyed the article and gained some additional insights. If you did, feel free to leave a clap! Constructive feedback is appreciated. Feel free to reach out to me here on linkedin or .

That’s all for this time , see you soon with another post.
Simarpreet Singh , signing off.
ਸਤਿ ਸ਼ੀ੍ ਅਕਾਲ 🙏

Medium article link:



  2. Wikipedia

Python3 #Detecting_Shapes #ImageProcessing #OpenCV

Top comments (1)

hsnsa profile image
Hassan Saei

How we can extract rectangle shape with If command, Please? In your code you extract with else. I need just to get rectangle shape please.