Если вы не возражаете против использования 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)
![Output](https://i.stack.imgur.com/W98LT.png)
Отказ от ответственности: я новичок в Python в целом, и особенно в Python API OpenCV (C ++ для победы). Комментарии, улучшения, выделение Python no-gos приветствуются!