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()
Hi there, I’m the founder of Pysource.
I’m a Computer Vision Consultant, developer and Course instructor.
I help Companies and Freelancers to easily and efficiently build Computer Vision Software.
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
Detect and Track any Object (Full Videocourse)
You can Build Software to detect and track any Object even if you have a basic programming knowledge.