python - 如何识别openCV中的不完整矩形

标签 python opencv image-processing image-segmentation scikit-image

我将如何从如下图所示的图像中识别和提取矩形。

请注意,我的矩形可能不完整并且有一些缺失的边,有些边可能是部分线。

谢谢!

image sample

最佳答案

这可以使用 morphological 解决诸如 eroding and dilating 之类的操作.这两个操作将有助于创建封闭的矩形。 之后,您可以使用此 page 中的教程检测矩形等简单形状。

我实现了一个快速演示,它适用于您提供的图像。


ma​​in.py:

import cv2
import numpy as np
from shapeDetector import ShapeDetector
import imutils

img = cv2.imread('t.png')
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(img,kernel,iterations = 10)
dilate = cv2.dilate(erosion,kernel,iterations = 10)

侵 eclipse 使所有线条变粗,因此要恢复到正常宽度,我们需要在侵 eclipse 后扩大。我建议对扩张操作进行一次评论,以了解侵 eclipse 是如何工作的,反之亦然。 此操作将像这样转换您的图像 this

我使用的检测算法需要黑色背景上的白线。 这就是我们需要反转图像的原因。

cv2.bitwise_not ( dilate, dilate )

之后,我们就可以使用教程中的代码了。

image = dilate
resized = imutils.resize(image, width=300)
ratio = image.shape[0] / float(resized.shape[0])

# convert the resized image to grayscale, blur it slightly,
# and threshold it
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
#thresh = dilate
# find contours in the thresholded image and initialize the
# shape detector
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
sd = ShapeDetector()

# loop over the contours
for c in cnts:
    # compute the center of the contour, then detect the name of the
    # shape using only the contour
    M = cv2.moments(c)
    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")
    cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
    cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX,
        0.5, (255, 255, 255), 2)

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

shapeDetector.py:

# import the necessary packages
import cv2

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

结果:

enter image description here

关于python - 如何识别openCV中的不完整矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44295099/

相关文章:

python - mustache 被定义为 1.5* IQR,python seaborn boxplot 中的两个 mustache 怎么会不同呢?

python - Pydub 导出错误 - 手动选择编码器

python - strftime 问题(python)

python - 如何检测图像上像素的相对深度?

opencv - 提高 SURF 在小图像上的性能

Python - Unicode 文件 IO

c++ - 加载关键点和绘图

opencv - 如何使用opencv从数组创建二值图像?

python - 将网络摄像头素材从OpenCV获取到PyQt

python - 使用 Python 在两个图像中查找匹配的数据点