【问题标题】:Count the number of rectangles in an image计算图像中矩形的数量
【发布时间】:2020-03-25 23:13:49
【问题描述】:

背景

我有两张图片,我想计算两张图片中矩形的数量。

我已经编写了一些查找轮廓的代码,并使用它来查找矩形。但它没有按预期工作,所以我需要一些帮助:

问题

我很困惑为什么代码会找到它所做的矩形数量。例如在第一张图片中,它计数为 8,我预计为 4。

第二个数为 16,我认为这是正确的(15 个内部,1 个外部)。

代码

我的代码如下:

import cv2
import numpy as np

pic = 'boxes1'
image = cv2.imread(f'../Computer Vision/{pic}.jpg', 1)

blur = cv2.pyrMeanShiftFiltering(image, 11, 21)
gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]

rect_list = []

for cont in contours:
    peri = cv2.arcLength(cont, True)
    approx = cv2.approxPolyDP(cont, 0.015 * peri, True)
    if len(approx) == 4:
        x,y,w,h = cv2.boundingRect(approx)
        rect = x,y,w,h
        rect_list.append(rect)
        cv2.rectangle(image,(x,y),(x+w,y+h),(36,255,12),2)

cv2.imshow('thresh', thresh)
cv2.imwrite(f'output_{pic}.png', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(len(rect_list))

电流输出

代码在第一个图像中找到 8 个矩形,在第二个图像中找到 16 个。我认为第一个应该是 4,第二个可能是正确的(?)(15 个内部和 1 个外部)。

代码保存了以下输出:

【问题讨论】:

  • 第一张图片有 8 个矩形,总是交替的白色和黑色

标签: python image opencv image-processing computer-vision


【解决方案1】:

观察到一个矩形正好有四个角,我们可以利用这一事实简单地计算图像中角的数量。图像中矩形的数量应该是角的数量除以四。方法如下:

  1. 获取二值图像。加载图像、灰度、Gaussian blurOtsu's threshold

  2. 去除小噪声。我们find contours然后使用cv2.contourArea使用轮廓区域过滤进行过滤,并通过使用cv2.drawContours填充轮廓来去除噪声。

  3. 查找角点。我们使用已实现为 cv2.goodFeaturesToTrack 的 Shi-Tomasi 角点检测器进行角点检测。查看this 以了解每个参数的说明。


以绿色突出显示的角

Rectangles: 4.0

Rectangles: 16.0

代码

import cv2

# Load image, grayscale, blur, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Remove small noise with contour area filtering
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area < 150:
        cv2.drawContours(thresh, [c], -1, 0, -1)

# Find corners and draw onto image
corners = cv2.goodFeaturesToTrack(thresh,150,0.5,5)
for corner in corners:
    x,y = corner.ravel()
    cv2.circle(image,(x,y),3,(36,255,12),-1)

# The number of rectangles is corners / 4
print('Rectangles: {}'.format(len(corners)/4))

cv2.imshow('image', image)
cv2.waitKey()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多