Question
Find the largest rectangular bounding box containing only ones in a 2d mask NumPy array
I have a 2d mask where I'd like to find the largest rectangular bounding box containing only ones.
Is there a more efficient way than determining all possibilities for bounding boxes and then comparing their size?
Example code:
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
mask = np.array([[0, 1, 0, 0, 0, 1, 0, 1], # example mask
[0, 0, 0, 1, 1, 0, 0, 1],
[1, 1, 0, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 1, 1],
[0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 1, 1]])
def find_largest_bbox(mask):
# TODO
return 3, 1, 4, 4
bbox = find_largest_bbox(mask)
plt.close()
plt.imshow(mask)
x, y = bbox[0] - 0.5, bbox[1] - 0.5
w, h = bbox[2] - bbox[0] + 1, bbox[3] - bbox[1] + 1
rect = patches.Rectangle((x, y), w, h, linewidth=2, edgecolor="red", facecolor="none")
plt.gca().add_patch(rect)
plt.show()