Monday 22 March 2021

opencv 21 detect geometric shapes


original image

apply threshold

draw contour and text
#main.py
import numpy as np
import cv2

img = cv2.imread('assets/geometric shapes.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 70, 80, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

for contour in contours:
    if cv2.contourArea(contour) < 2000:
        continue
    #polyDP (contour, accuracy, shape closed?)
    approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
    cv2.drawContours(img, [approx], 0, (255, 255 , 255), 1)
    #print(approx)
    x = approx.ravel()[0]
    y = approx.ravel()[1] - 15

    if len(approx) == 3:
        cv2.putText(img, 'triangle', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))
    elif len(approx) == 4:
        x, y, w, h = cv2.boundingRect(approx)
        aspectRatio = float(w)/h
        if aspectRatio >= 0.95 and aspectRatio <= 1.05:
            cv2.putText(img, 'square', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))
        else:
            cv2.putText(img, 'rectangle', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))
    elif len(approx) == 5:
        cv2.putText(img, 'pentagon', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))
    elif len(approx) == 6:
        cv2.putText(img, 'hexagon', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))
    elif len(approx) == 7:
        cv2.putText(img, 'heptagon', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))
    elif len(approx) == 8:
        cv2.putText(img, 'octagon', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))
    elif len(approx) == 9:
        cv2.putText(img, 'nonagon', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))
    elif len(approx) == 10:
        cv2.putText(img, 'star', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))
    else:
        cv2.putText(img, 'circle', (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255))

cv2.imshow('threshold', thresh)
cv2.imshow('contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

reference:

No comments:

Post a Comment