作为表面的检测表给出了许多矩形

问题描述 投票:0回答:1

我想获得桌子表面的矩形。所以我想我可以使用带有findContours和outlineArea函数的opencv来做到这一点。现在,当结果是当我采用最大轮廓面积时,它将一切都作为一个区域。当我不这样做时,会得到不同的结果,请参见图片。

Green rectangle over the whole image

Rectangles everywhere

是否有一种组合矩形的方式,以便它将表格检测为表面?因为我想知道这些东西是在表面上还是从表面上移开。

代码:

import cv2
import numpy as np

file = "/Users/mars/Downloads/table.jpg"

im1 = cv2.imread(file, 0)
im = cv2.imread(file)

ret, thresh_value = cv2.threshold(im1, 180, 255, cv2.THRESH_BINARY_INV)

kernel = np.ones((5, 5), np.uint8)
dilated_value = cv2.dilate(thresh_value, kernel, iterations=1)

contours, hierarchy = cv2.findContours(dilated_value, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt = contours[max_index]
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2)

cv2.imwrite('result.jpg', im)
python numpy opencv opencv-contour
1个回答
2
投票

您的代码不起作用的主要原因是因为您正在使用cv2.THRESH_BINARY_INV。反转极性,将工作台区域变为黑色,并且findContours正在搜索白色轮廓。

我建议使用以下阶段:

  • 转换为二进制图像-使用THRESH_OTSU作为自动阈值(比使用固定阈值更健壮)。
  • 使用“闭合”形态操作(闭合就像膨胀而不是侵蚀)。闭合比dilate好,因为它不会改变轮廓的大小。
  • 查找轮廓,使用RETR_EXTERNAL而不是RETR_TREE,因为您正在寻找外部轮廓。
  • 查找具有最大面积的轮廓。

这里是代码:

import numpy as np
import cv2

# Read input image
im = cv2.imread('table.jpg')

# Drop one row and column from each side (because the image you posted has a green rectangle around it).
im = im[1:-2, 1:-2, :]

# Convert to Grayscale
im1 = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

# Convert to binary image - use THRESH_OTSU for automatic threshold.
ret, thresh_value = cv2.threshold(im1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# Use "closing" morphological operation (closing is like dilate and than erode)
thresh = cv2.morphologyEx(thresh_value, cv2.MORPH_CLOSE, np.ones((5, 5)))

cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]  # [-2] indexing is used due to OpenCV compatibility issues.

# Get contour with maximum area
c = max(cnts, key=cv2.contourArea)

# Mark contour with green line
cv2.drawContours(im, [c], -1, (0, 255, 0), 2)


# Show output
cv2.imshow('im', cv2.resize(im, (im.shape[1]//4, im.shape[0]//4)))
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.