单个轮廓的边界框,一种颜色除外

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

我有下面的图像

enter image description here

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

enter image description here

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

将某些区域恢复为非连续区域(左侧有2条垂直线),您可以忽略它。我将扩张并使它们连续。

python-3.x opencv-contour opencv-python
1个回答
1
投票

如果我了解您想要的,这是Python / OpenCV中的一种方法。

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

输入:

enter image description here

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)

阈值图像:

enter image description here

边界框:

enter image description here

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