如何对轮廓进行分组并绘制单个边界矩形

Ati*_*esh 2 python opencv python-3.x opencv-contour

我需要分组contours并绘制一个bounding rectangle包含所有轮廓的单曲,就像这样

在此处输入图片说明

from matplotlib import pyplot as plt
import cv2 as cv

img = cv.imread('shapes1.png', 0)
imgRGB = cv.cvtColor(img.copy(), cv.COLOR_GRAY2RGB)

_, ctrs, _ = cv.findContours(img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

boxes = []
for ctr in ctrs:
    x, y, w, h = cv.boundingRect(ctr)
    boxes.append([x, y, w, h])

for box in boxes:
    top_left     = (box[0], box[1])
    bottom_right = (box[0] + box[2], box[1] + box[3])
    cv.rectangle(imgRGB, top_left, bottom_right, (0,255,0), 2)

fig = plt.figure(figsize = (10, 10))
ax  = fig.add_subplot(111)
ax.imshow(imgRGB, cmap='gray')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

是否有任何直接的方法来做到这一点,而不是以编程方式合并所有边界矩形

Han*_*rse 5

如果您不介意使用numpy,您可以简单地concatenate从那里使用该函数,请参阅以下代码。注意:我使用的是 OpenCV 4.0.0,其中返回值的顺序findContours不同。

import cv2
import numpy as np

# Input image
input = cv2.imread('images/kchZb.png', cv2.IMREAD_GRAYSCALE)

# Modify input image to extract "original" image
_, input = cv2.threshold(input[10:400, 40:580], 224, 255, cv2.THRESH_BINARY)

# Find contours
cnts, _ = cv2.findContours(input, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Concatenate all contours
cnts = np.concatenate(cnts)

# Determine and draw bounding rectangle
x, y, w, h = cv2.boundingRect(cnts)
cv2.rectangle(input, (x, y), (x + w - 1, y + h - 1), 255, 2)

# Output image
cv2.imwrite('images/output.png', input)
cv2.imshow('Input', input)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)

输出

免责声明:总的来说,我是 Python 的新手,特别是 OpenCV 的 Python API(C++ 用于 win)。非常欢迎评论、改进、突出显示 Python 禁忌!