我可以在OpenCV中做什么以更好地识别圈子?

时间:2019-03-11 08:21:30

标签: python opencv detection shapes

所以这是我的问题,我需要能够识别和计算项目的形状,并且遇到一个小困难。我刚刚开始使用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

1 个答案:

答案 0 :(得分:0)

我通过重新组织代码并添加

解决了我的问题
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

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