Simple shape detection – Opencv with Python 3

We’ll se in this video how to perform a simple shape detection.
Starting from an image with a few shapes, we’ll be able to detect exactly each shape (rectangle, circle, pentagon, etc.) and the position.

As first thing we need to import the libraries, then on line 4 we also define the font that we will use later on to display the text on the image.

import cv2
import numpy as np


We then load the image, we get the threshold of the image to have a black and white image, where the background is white and all the shapes are black.

From the black and white image we find the contours, so the boundaries of all the shapes.

img = cv2.imread("shapes.jpg", cv2.IMREAD_GRAYSCALE)
_, threshold = cv2.threshold(img, 240, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

We loop trough the contours, so we get the coordinates of the contours of each single shape.
On line 10 we approximate the contours to remove the noise.

for cnt in contours:
    approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
    cv2.drawContours(img, [approx], 0, (0), 5)
    x = approx.ravel()[0]
    y = approx.ravel()[1]

    if len(approx) == 3:
        cv2.putText(img, "Triangle", (x, y), font, 1, (0))
    elif len(approx) == 4:
        cv2.putText(img, "Rectangle", (x, y), font, 1, (0))
    elif len(approx) == 5:
        cv2.putText(img, "Pentagon", (x, y), font, 1, (0))
    elif 6 < len(approx) < 15:
        cv2.putText(img, "Ellipse", (x, y), font, 1, (0))
        cv2.putText(img, "Circle", (x, y), font, 1, (0))

Finally we display everything on the screen:

cv2.imshow("shapes", img)
cv2.imshow("Threshold", threshold)

Learn to build Computer Vision Software easily and efficiently.

This is a FREE Workshop where I'm going to break down the 4 steps that are necessary to build software to detect and track any object.

Sign UP for FREE