DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on • Updated on

Shape Detection OpenCV Python

Shape Detection OpenCV Algorithm

First of all, read and store the image. For this example, I am taking an image that contains shapes like triangle, square, rectangle, and circle.

The image is then converted to grayscale using the cvtColor() function.

The Grayscaled image is then thresholded using the THRESH_BINARY Method. The Thresholded image is then taken and contours are found on that image.

The Contours obtained are then looped and the edges are counted using the approxPolyDP() function, which takes each contour.

The edges of the Contour is then drawn on the image using drawContours() function.

To write the name of the shape blocks of if-else are used that take decisions on the basis of the number of edges.

Example: If three edges are found the shape will be a triangle.

In the case of square and rectangle aspect ratio between the width and height is calculated. If the ratio is close to 1 then the shape is square else rectangle.

If no edges are found then it is likely to be a circle.

Read more and the full source code from Shape Detection OpenCV Python.

Top comments (0)