Detecting Geometrical Shapes in an image using OpenCV
Tags: python, opencv, machinelearning, computerscience
Published: 2020-06-21 09:15:36


Well I was just exploring OpenCV library of python in this quarantine , and going through that, I came across term 
Contour.
> 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

```python
import numpy as np
import cv2
``` 
---

  

{% gist https://gist.github.com/simarpreetsingh-019/98e294da41f4da117ef376ce0b55ed7e %}

2. Import image and convert to grayscale image.

3. Applying thresholding on image and then finding contours.
---

```python
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)
```
--- 

{% gist https://gist.github.com/simarpreetsingh-019/51cdb1abcc81c3954fe3a805e6c1d7e8 %}

“ _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.

_Next_:
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()_**.

{% gist https://gist.github.com/simarpreetsingh-019/b5e8604b760970add613b527e02b22d4 %}

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](https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm) algorithm. Check the wikipedia page for algorithm and demonstration._

example of how approxpolyDp() works.

![Alt Contour shape](https://miro.medium.com/max/1214/0*mkGxCvPJZLv2U3fk.jpg)

**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_**


{% gist https://gist.github.com/simarpreetsingh-019/f48014abc9fb2c13c7f750c7fe1a053b %}

and our Program runs successfully.
Image used :
![Alt Image used](https://miro.medium.com/max/722/0*-Z0nGGI02DVLUtfA)

Output of code:
![Alt output of code](https://miro.medium.com/max/728/0*7nEs6DoTJqqeFYcD)

**Whole code available 👇:**

{% gist https://gist.github.com/simarpreetsingh-019/b37a50150122a7e576056d4265ee1d55 %}

-------------------------------------------------

Github link to this repo 👇:
{% github https://github.com/simarpreetsingh-019/openCV-Learning/ %}

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](https://www.linkedin.com/in/simarpreetsingh019/) or simarpreetsingh.019@gmail.com .

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

Medium article link: {% medium https://medium.com/simply-dev/detecting-geometrical-shapes-in-an-image-using-opencv-bad67c40174f %}

References:
1. <https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_table_of_contents_contours/py_table_of_contents_contours.html>

2. Wikipedia

 Python3 #Detecting_Shapes #ImageProcessing #OpenCV