首页 > 解决方案 > 我可以在 OpenCV 中做什么来更好地识别圆圈?

问题描述

所以这是我的问题,我需要能够识别和计算项目的形状并且遇到了一个小困难。我刚刚开始使用 OpenCV,并且在不使用 else 命令的情况下无法找到更好的方法来识别圆圈。例如,如果框架中的其他任何形状不是其他形状之一,它会将其检测为圆形(理想情况下,我希望能够忽略框架中的那些对象。)我不确定如果这会影响除这部分代码之外的任何内容,我将使用自适应阈值和高斯模糊来帮助提高处理能力。

TLDR:我正在尝试找到一种不使用 else 语句来识别圆圈的方法。

def detect(self, c):
    # initialize the shape name and approximate the contour
    shape = "unidentified"
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)

    # if the shape is a triangle, it will have 3 vertices
    if len(approx) == 3:
        shape = "triangle"
        self.s2 = self.s2 + 1

    # if the shape has 4 vertices, it is either a square or
    # a rectangle
    elif len(approx) == 4:
        # compute the bounding box of the contour and use the
        # bounding box to compute the aspect ratio
        (x, y, w, h) = cv2.boundingRect(approx)
        ar = w / float(h)

        # a square will have an aspect ratio that is approximately
        # equal to one, otherwise, the shape is a rectangle
        if 0.75 <= ar <= 1.35:
            shape = "square"
            self.s3 = self.s3 + 1
        else:
            shape = "rectangle"
            self.s4 = self.s4 + 1

    # otherwise, we assume the shape is a circle
    else:
        shape = "circle"
        self.s5 += 1

标签: pythonopencvdetectionshapes

解决方案


我通过大量重新组织我的代码并添加来解决我的问题

if shape == "circle":
    circles = cv2.HoughCircles(thresh,cv2.HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=0,maxRadius=0)
    if circles is not None:
        s5 += 1

到代码的新区域。谢谢大家的帮助。


推荐阅读