【发布时间】:2022-01-22 14:09:15
【问题描述】:
我不想突出显示与其他框部分重叠或不与任何其他框重叠的边界框。我试图通过检测轮廓来做到这一点:
import cv2
# Read input image
img = cv2.imread('image.png')
# Convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply threshold
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Find contours and hierarchy
cnts, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2:]
# Draw all contours with green color for testing
cv2.drawContours(img, cnts, -1, (0, 255, 0))
# Hierarchy Representation in OpenCV
# So each contour has its own information regarding what hierarchy it is,
# who is its child, who is its parent etc.
# OpenCV represents it as an array of four values : [Next, Previous, First_Child, Parent]
# Iterate contours and hierarchy:
for c, h in zip(cnts, hier[0]):
# Check if contour has one partent and one at least on child:
if (h[3] >= 0) and (h[2] >= 0):
# Get the partent from the hierarchy
hp = hier[0][h[3]]
# Check if the parent has a parent:
if hp[3] >= 0:
# Get bounding rectange
x, y, w, h = cv2.boundingRect(c)
# Draw red rectange for testing
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), thickness=1)
# Show result for testing
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
但它会选择图像中的每个轮廓。例如,如果这是原始图像:
那么这就是我运行上面代码时得到的结果:
如何首先仅检测此图像中的边界框,其次仅突出显示完全 100% 位于另一个边界框内的边界框?
【问题讨论】:
-
您应该首先了解获取用于绘制这些框的数据。从绘制的图像中提取它们对我来说似乎有点愚蠢。
标签: python opencv computer-vision bounding-box opencv-contour