【问题标题】:Bounding boxes for individual contours except one color单个轮廓的边界框,一种颜色除外
【发布时间】:2020-04-10 03:42:59
【问题描述】:

我有一张如下图

我想使用 OpenCV 和 Python 为每个区域添加边界框,如下图所示

我现在如何找到轮廓是该区域是一种颜色。但是,在这里我想找到所有非黑色区域的轮廓。我只是无法弄清楚。有人可以帮忙吗?

重新分级某些区域是不连续的区域(左侧有 2 条垂直线),您可以忽略它。我会扩张并使它们连续。

【问题讨论】:

  • 你的问题不清楚。什么轮廓是黑色的?猜猜你的意思,将你的输入转换为灰度和阈值。然后从中获取轮廓,然后在原始图像上绘制它们。
  • 很抱歉给您带来了困惑。我的意思是除了背景黑色之外的所有东西的轮廓。你能告诉我如何阈值(遮罩)除黑色之外的所有东西吗?另一个问题的链接也将很有用。谢谢。

标签: python-3.x opencv-contour opencv-python


【解决方案1】:

如果我明白你想要什么,这是 Python/OpenCV 中的一种方法。

  • 读取输入
  • 转换为灰色
  • 黑白阈值
  • 查找外部轮廓及其边界框
  • 在输入副本上绘制边界框矩形
  • 保存结果

输入:

import cv2
import numpy as np

# read image
img = cv2.imread('white_green.png')

# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]\

# get contour bounding boxes and draw on copy of input
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours = contours[0] if len(contours) == 2 else contours[1]
result = img.copy()
for c in contours:
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(result, (x, y), (x+w-1, y+h-1), (0, 0, 255), 1)

# view result
cv2.imshow("threshold", thresh)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save result
cv2.imwrite("white_green_thresh.jpg", thresh)
cv2.imwrite("white_green_bboxes.jpg", result)


阈值图像:

边界框:

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 2013-01-22
    • 2019-03-03
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    相关资源
    最近更新 更多