我有一个 2d 掩模,我想在其中找到仅包含矩形边界框的最大矩形边界框。
有没有比确定边界框的所有可能性然后比较它们的大小更有效的方法?
示例代码:
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()
lir
(使用 Numba):
# takes some time for compilation..
import largestinteriorrectangle as lir
def find_largest_bbox(mask):
return lir.lir(mask.astype("bool"))
x, y, w, h = find_largest_bbox(mask)
im = plt.imshow(mask)
xp, *_, yp = im.get_extent()
plt.gca().add_patch(
patches.Rectangle(
(x + xp, y + yp), w, h,
lw=2, fc="none", ec="r",
)
)