Python|使用 OpenCV 检测图像中的多边形
方法:我们将用于检测给定多边形的形状的方法将基于根据它具有的边数对检测到的形状进行分类。例如,如果检测到的多项式有 3 条边,则可以将其视为三角形,如果多项式有 4 条边,则可以将其分类为正方形或矩形。
先决条件:
- 确保您的计算机上已经安装了 Python3、OpenCV、numpy。
- 有关 OpenCV 的基础知识会有所帮助 – OpenCV 基础知识
- 确保将要检测形状的图像保存在本地目录中
实现:在下面的代码中,我们将从图像“arrow.jpg”中检测一个箭头形状的对象。将根据形状的边数检测形状
代码:检测图像中多边形的Python程序
# Python code to detect an arrow (seven-sided shape) from an image.
import numpy as np
import cv2
# Reading image
img2 = cv2.imread('arrow.jpg', cv2.IMREAD_COLOR)
# Reading same image in another variable and
# converting to gray scale.
img = cv2.imread('arrow.jpg', cv2.IMREAD_GRAYSCALE)
# Converting image to a binary image
# (black and white only image).
_,threshold = cv2.threshold(img, 110, 255,
cv2.THRESH_BINARY)
# Detecting shapes in image by selecting region
# with same colors or intensity.
contours,_=cv2.findContours(threshold, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
# Searching through every region selected to
# find the required polygon.
for cnt in contours :
area = cv2.contourArea(cnt)
# Shortlisting the regions based on there area.
if area > 400:
approx = cv2.approxPolyDP(cnt,
0.009 * cv2.arcLength(cnt, True), True)
# Checking if the no. of sides of the selected region is 7.
if(len(approx) == 7):
cv2.drawContours(img2, [approx], 0, (0, 0, 255), 5)
# Showing the image along with outlined arrow.
cv2.imshow('image2', img2)
# Exiting the window if 'q' is pressed on the keyboard.
if cv2.waitKey(0) & 0xFF == ord('q'):
cv2.destroyAllWindows()
注:阈值中的参数“110”可以根据需要调整,如果对象是不同的颜色,是基于反复试验。
结果 :
带箭头的图像
二进制图像
概述的箭头