繁体   English   中英

如何在python opencv中将多个边界框合并为一个

[英]How to merge multiple bounding box into one in python opencv

我有检测颜色的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()

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

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()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM