你可以使用OpenCV来完成这个任务。
import cv2
img = cv2.imread('input.png', 0)
h, w = img.shape[:2]
imgray = 255 - img
ret, thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
rects = [cv2.boundingRect(cnt) for cnt in contours]
top_x = min([x for (x, y, w, h) in rects])
top_y = min([y for (x, y, w, h) in rects])
bottom_x = max([x+w for (x, y, w, h) in rects])
bottom_y = max([y+h for (x, y, w, h) in rects])
out = cv2.rectangle(img, (top_x, top_y), (bottom_x, bottom_y), (0, 255, 0), 2)
cv2.imwrite('out.jpg', img)
示例输出![在此输入图片描述](https://istack.dev59.com/qkO2n.webp)