你需要做的是使用cv2.findContours()找到给定图像中的所有轮廓,然后找到每个轮廓的边界矩形并在所有轮廓矩形中找到minX,minY,maxX,maxY,这会给你一个外部边界矩形,它涵盖了所有较小的轮廓,因此是您想要的结果。
import cv2
import numpy as np
img = cv2.imread("/Users/anmoluppal/Downloads/mjut8.png", 0)
# Threshold and Invert the image to find the contours
ret, thresh = cv2.threshold(img, 10, 255, cv2.THRESH_BINARY_INV)
# Find the contours
im, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
x, y, r, b = [img.shape[1]/2, img.shape[0]/2, 0, 0]
# Iterate over all the contours, and keep updating the bounding rect
for cnt in contours:
rect = cv2.boundingRect(cnt)
if rect[0] < x:
x = rect[0]
if rect[1] < y:
y = rect[1]
if rect[0] + rect[2] > r:
r = rect[0] + rect[2]
if rect[1] + rect[3] > b:
b = rect[1] + rect[3]
bounding_rect = [x, y, r-x, b-y]
# Debugging Purpose.
cv2.rectangle(img, (x, y), (r, b), np.array([0, 255, 0]), 3)