从Flowchart OpenCV中检测手绘形状

时间:2016-09-09 09:19:09

标签: python c++ opencv object-detection

我是OpenCV的新手,我需要一些关于我正在做的事情的指导。基本上我有这个手绘流程图,我需要识别流程图的形状

以下是我绘制的流程图

imageOriginal

我已经编写了一些代码来检测Python OpenCV3中的形状

image = cv2.imread("images/trackShape.jpg")
orig = image.copy()
resized = imutils.resize(image, width=300)
ratio = image.shape[0] / float(resized.shape[0])

#convert the image to grayscale, blur it, and find edges in the image
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
grayFilter = cv2.bilateralFilter(gray, 11, 17, 17)
edged = cv2.Canny(grayFilter, 30, 200)

#find contours in the edged image
_,cnts, hierarchy = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

sd = ShapeDetector()

这是ShapeDetector的功能

class ShapeDetector:
def __init__(self):
    pass

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"

    # 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
        shape = "square" if ar >= 0.95 and ar <= 1.05 else "rectangle"

    # if the shape is a pentagon, it will have 5 vertices
    elif len(approx) == 5:
        shape = "pentagon"

    # otherwise, we assume the shape is a circle
    else:
        shape = "circle"

    # return the name of the shape
    return shape

这是我找到轮廓的地方

for c in cnts:

M = cv2.moments(c)

if M["m00"] > 0:

    cX = int((M["m10"] / M["m00"]) * ratio)
    cY = int((M["m01"] / M["m00"]) * ratio)
    shape = sd.detect(c)

    # multiply the contour (x, y)-coordinates by the resize ratio,
    # then draw the contours and the name of the shape on the image
    c = c.astype("float")
    c *= ratio
    c = c.astype("int")

    # draw border around the screen

    cv2.drawContours(image, [c], -1, (0, 255, 0), 3)

    cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX,
                0.5, (255, 255, 255), 2)

    resized = imutils.resize(image, width=600)
    cv2.imshow("RESULT", resized)
    cv2.waitKey(0)

不幸的是,这是我得到的结果 resut

正如你所看到的,它以某种方式将整个事物标记为矩形。这是因为线条将矩形,三角形和圆形连接在一起,因此它被检测为一个整体轮廓。

我如何断开每个形状的线条,以便能够正确识别形状。

提供的代码很好,以便我可以分析和研究它。非常感谢你

0 个答案:

没有答案