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 font = cv2.FONT_HERSHEY_COMPLEX
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() y = approx.ravel() 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)) else: cv2.putText(img, "Circle", (x, y), font, 1, (0))
Finally we display everything on the screen:
cv2.imshow("shapes", img) cv2.imshow("Threshold", threshold) cv2.waitKey(0) cv2.destroyAllWindows()
This site uses Akismet to reduce spam. Learn how your comment data is processed.
- Find and Draw Contours – OpenCV 3.4 with python 3 Tutorial 19
- Simple shape detection – Opencv with Python 3
- Feature detection (SIFT, SURF, OBR) – OpenCV 3.4 with python 3 Tutorial 25
- Check if two images are equal with Opencv and Python
- Lines detection with Hough Transform – OpenCV 3.4 with python 3 Tutorial 21