【问题标题】:How to merge multiple bounding box into one in python opencv如何在python opencv中将多个边界框合并为一个
【发布时间】:2022-06-29 02:36:25
【问题描述】:

我有检测颜色的 python 代码。一旦检测到颜色,我就会找到轮廓并绘制它们。以下是原图:

下面是带有轮廓和边界框的图像:

如您所见,检测到很多轮廓,因此存在多个边界框。有没有办法将这些边界框合并为一个。下面是代码

import cv2
import imutils
import numpy as np

image = cv2.imread("L00001.png")
image = imutils.resize(image, width=800)

hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower_bound = np.array([45, 150, 20])
upper_bound = np.array([75, 305, 255])
origMask = cv2.inRange(hsv, lower_bound, upper_bound)
contours, h = cv2.findContours(origMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    new = np.vstack(contours)
    area = cv2.contourArea(c)
    if area > 10:
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), (0, 0, 255), 2)

cv2.imshow("FRAME", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

【问题讨论】:

  • 我建议您查看您的 origMask 并查看是否可以调整颜色范围。如果做不到这一点,也许在得到你的轮廓之前使用一些形态来关闭和间隙。
  • 我喜欢@fmw42 的建议。蛮力的方法是通过轮廓边界框搜索 min(x)、min(y) 和 max(x)、max(y),这将为您提供角点。
  • 我已经能够通过使用连通分量分析来做到这一点。将尽快回答并发布代码

标签: python bounding-box opencv-contour color-detection


【解决方案1】:

我已经能够使用连通分量分析来做到这一点。在此之前我还应用了膨胀,输出看起来令人满意

import cv2
import imutils
import numpy as np
from skimage import measure
from imutils import contours

image = cv2.imread("L00001.png")
image = imutils.resize(image, width=800)

hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower_bound = np.array([45, 150, 20])
upper_bound = np.array([75, 305, 255])
origMask = cv2.inRange(hsv, lower_bound, upper_bound)
thresh = cv2.threshold(origMask, 200, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.erode(thresh, None, iterations=1)
thresh = cv2.dilate(thresh, None, iterations=6)

labels = measure.label(thresh, neighbors=4, background=0)
mask = np.zeros(thresh.shape, dtype="uint8")
for label in np.unique(labels):
    if label == 0:
        continue
    labelMask = np.zeros(thresh.shape, dtype="uint8")
    labelMask[labels == label] = 255
    numPixels = cv2.countNonZero(labelMask)
    if numPixels > 30:
        mask = cv2.add(mask, labelMask)

cnts, h = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for (i, c) in enumerate(cnts):
    area = cv2.contourArea(c)
    if area > 10:
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), (0, 0, 255), 2)

cv2.imshow("FRAME", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2021-12-16
    • 2018-02-05
    • 2021-10-20
    • 2015-07-13
    • 2022-01-07
    相关资源
    最近更新 更多