如何使用 OpenCV Python 检测图像中的三角形?

opencvpythonserver side programmingprogramming

要检测图像中的三角形,我们首先检测图像中的所有轮廓。然后我们循环遍历所有轮廓。找到每个轮廓的近似轮廓。如果近似轮廓中的顶点数为 3,则绘制轮廓并将其设置为三角形。请参阅下面的伪代码。

for cnt in contours:
    approx = cv2.approxPolyDP()
    if len(approx) == 3:
        cv2.drawContours()
        cv2.putText("Triangle")

步骤

您可以使用以下步骤检测输入图像中的三角形 −

导入所需的库。在以下所有 Python 示例中,所需的 Python 库都是 OpenCV。确保您已经安装了它。

import cv2

使用 cv2.imread() 读取输入图像并将其转换为灰度。

img = cv2.imread('approx1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

对灰度图像应用阈值以创建二值图像。调整第二个参数以获得更好的轮廓检测。

ret,thresh = cv2.threshold(gray,50,255,0)

使用 cv2.findContours() 函数查找图像中的轮廓。

contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

从轮廓列表中选择一个轮廓(比如第一个轮廓)cnt。或者循环遍历所有轮廓。

使用 cv2.approxPolyDP() 函数计算每个轮廓 cnt 的近似轮廓点。

approx = cv2.approxPolyDP(cnt,epsilon,True)

如果近似轮廓 approx 中的顶点为 3,则在图像上绘制轮廓并将其设置为三角形。

显示绘制轮廓和近似轮廓的图像。

cv2.imshow("Shapes", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

让我们看一些例子以便更好地理解。

示例1

在下面的 Python 代码中,我们检测输入图像中的三角形。

# import required libraries import cv2 # read the input image img = cv2.imread('shapes.jpg') # convert the image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply thresholding to convert the grayscale image to a binary image ret,thresh = cv2.threshold(gray,50,255,0) # find the contours contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print("Number of contours detected:",len(contours)) for cnt in contours: approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True) if len(approx) == 3: img = cv2.drawContours(img, [cnt], -1, (0,255,255), 3) # compute the center of mass of the triangle M = cv2.moments(cnt) if M['m00'] != 0.0: x = int(M['m10']/M['m00']) y = int(M['m01']/M['m00']) cv2.putText(img, 'Triangle', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2) cv2.imshow("Shapes", img) cv2.waitKey(0) cv2.destroyAllWindows()

我们将使用以下图像作为上述程序代码中的输入文件 -

输出

执行上述代码时,它将在控制台上生成以下输出

Number of contours detected: 4

我们得到以下窗口,显示输出-

在上面的输出图像中,一个三角形是检测到。

示例 2

在此示例中,我们将展示如何检测图像中的多个三角形。

import cv2 import numpy as np img = cv2.imread('shapes1.jpg') img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(img1,150,255,0) contours,hierarchy = cv2.findContours(thresh, 1, 2) print("Number of contours detected:",len(contours)) for cnt in contours: approx = cv2.approxPolyDP(cnt, 0.1*cv2.arcLength(cnt, True), True) if len(approx) == 3: img = cv2.drawContours(img, [cnt], -1, (0,255,255), 3) M = cv2.moments(cnt) if M['m00'] != 0.0: x = int(M['m10']/M['m00']) y = int(M['m01']/M['m00']) cv2.putText(img, 'Triangle', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2) cv2.imshow("Triangles", img) cv2.waitKey(0) cv2.destroyAllWindows()

我们将使用以下图像作为此程序中的输入文件 -

输出

执行上述代码时,它将在控制台上产生以下输出 -

Number of contours detected: 6

我们得到以下窗口,显示输出 -

在上面的输出图像中,我们检测到了四个三角形。


相关文章