【问题标题】:Get the count of rectangles in an image获取图像中矩形的数量
【发布时间】:2017-11-23 06:08:21
【问题描述】:

我有一张像下面这样的图像,我想确定图像中矩形的数量。如果他们被填满,我知道该怎么做。

contours = cv2.findContours(image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if imutils.is_cv2() else contours[1]
print len(contours)

但是如果矩形是空的,这不起作用。

我也不知道如何填充图像中的矩形。如果轮廓是使用 OpenCV 绘制的,我知道如何填充它们,但我不知道如何填充图像中已经存在的空矩形。

【问题讨论】:

  • 您的问题找到解决方案了吗?

标签: python c++ opencv image-processing


【解决方案1】:

假设您尝试过形状检测器、线检测器等,但在这里没有成功,这是解决此问题的另一种方法。

如果这是一张灰度 PNG 图像,您可以使用按颜色分割来实现此目的。 我会这样处理它:

count = 0
For each pixel in the image:
    if color(pixel) == white /*255*/
        count++
        floodfill using this pixel as a seed pixel and target color as count

no_of_rectangles = count - 1 /* subtract 1 since the background will be colored too*/

这假设矩形有连续的线,否则填充将泄漏到其他矩形中。

【讨论】:

    【解决方案2】:

    如果您找到外部轮廓(RETR_EXTERNAL),填充与否应该没有区别。以下代码将为您提供数字 3。

    canvas = np.zeros(img.shape, np.uint8)
    img2gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    ret,thresh = cv2.threshold(img2gray,128,255,cv2.THRESH_BINARY_INV)
    im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    
    print(len(contours))
    
    for cont in contours:
        cv2.drawContours(canvas, cont, -1, (0, 255, 0), 3)
    
    cv2.imshow('contours',canvas)
    cv2.waitKey(30000)
    cv2.destroyAllWindows()
    

    请注意,如果您在 findContours() 中使用 RETR_TREE 作为第二个参数,您将获得所有 6 个轮廓,包括内部轮廓。

    显然,这假设图像仅包含矩形,并且不区分不同的形状。

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 1970-01-01
      • 2015-07-11
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      相关资源
      最近更新 更多