在二进制对象周围指定一个矩形来定义空间受限区域?

Specifying a rectangle around a binary object to define a spatially-constrained area?

我正在 python 编程。我有二进制图像中对象中心的坐标。如何定义 python 中对象周围的边界框区域,它从左上角的最非零点开始,到右下角的最下点结束?

我想考虑对象周围的矩形区域,以在空间上和虚拟上限制算法的工作区域。为此,如何检查一个点是否落在该区域?

感谢您的帮助

在我的脑海中,因为你知道物体的中心但不知道它的形状或它的 height/width,我会通过在图像中找到连接的组件来做到这一点。在 Opencv 中,这可以通过 connectedComponents 函数来完成。查看 this post 中的示例,解释如何从 python 调用它。此函数经过了相当优化,因此除非您想进行 real-time compute-intensive 优化,否则您可以使用它而不会注意到任何开销。

一旦有了连接的组件,就可以对每个组件的像素进行排序(一次根据水平组件,一次根据垂直组件),并获得形式为 [left,right,top,bottom] 的边界框.在那之后,检查一个点是否落在它里面是微不足道的。

我发现了一个很简单的方法:

首先,我使用 numpy.argwhere

找到了非零值的索引(这里我的值为 1)
pp=np.argwhere(img==1)

它会给出这样的坐标:

[[ 95  63]
 [ 95  64]
 [ 95  65]
 ...
 [197  71]
 [198  68]
 [198  69]]

然后,

min_point=np.min(pp[:],axis=0)   #output: [95  0] 
max_point=np.max(pp[:],axis=0)   #output: [198 123]
height=max_point[0]-min_point[0]+1  #height=104
width=max_point[1]-min_point[1]+1  #width=124

起点是(0,95),终点是(123,198),我如图所示:

from matplotlib.patches import Rectangle
fig, ax = plt.subplots(1)
ax.imshow(img, cmap=plt.cm.gray)
ax.axis('off')
ax.add_patch(Rectangle((0,95),124,104,alpha=0.6))
plt.show(fig)

您可以按照 Contour Features tutorial 中所述使用 boundingRect 函数:

img.png如下:

import cv2
import numpy as np

img = cv2.imread('img.png')
active_px = np.argwhere(img!=0)
active_px = active_px[:,[1,0]]
x,y,w,h = cv2.boundingRect(active_px)
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),1)
cv2.imwrite('result.png',img)

result.png 如下: