在UML图,openCV中检测矩形轮廓不准确

时间:2018-09-24 13:47:09

标签: opencv

我想使用OpenCV从jpg格式的UML序列图的顶部提取一些矩形。

我使用的算法发现太多的矩形,这些矩形非常小且不需要。

我认为问题出在代码开头的某个地方,我在其中应用了canny边缘检测,但是我不确定。

我只想捕获顶部和中心的大矩形。

感谢您的帮助。

original diagram After running code

import cv2
import numpy as np
import imutils

image = cv2.imread("./diagrams/sd2.jpg")

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 90, 150, 3)
cnts = cv2.findContours(edges, cv2.RETR_EXTERNAL,
                        cv2.CHAIN_APPROX_SIMPLE)


cnts = cnts[0] if imutils.is_cv2() else cnts[1]

cv2.drawContours(image, cnts, -1, (0, 255, 0), 1)


def detect(c):
    shape = "unidentified"
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.03 * peri, True)

    if len(approx) == 4:
        (x, y, w, h) = cv2.boundingRect(approx)
        ar = w / float(h)

        shape = "square" if ar >= 0.95 and ar <= 1.05 else "rectangle"

    return shape


# loop over the contours
for c in cnts:
    M = cv2.moments(c)
    if M["m00"] != 0:
        cX = int((M["m10"] / M["m00"]))
        cY = int((M["m01"] / M["m00"]))

        shape = detect(c)

        c = c.astype("float")
        c = c.astype("int")

        if(shape == "rectangle"):
            cv2.drawContours(image, [c], -1, (0, 255, 0), 2)

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

# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)

0 个答案:

没有答案