Skip to main content
 首页 » 编程设计

python之如何在 python 中获取给定像素标签的对象边界框

2025年05月04日11kerrycode

假设我有一个图像的场景解析图,这个场景解析图中的每个像素都表示这个像素属于哪个对象。现在我想获取每个对象的边界框,如何在 python 中实现它? 对于一个详细的例子,假设我有一个这样的场景解析图:

0 0 0 0 0 0 0 
0 1 1 0 0 0 0 
1 1 1 1 0 0 0 
0 0 1 1 1 0 0 
0 0 1 1 1 0 0 
0 0 0 0 0 0 0 
0 0 0 0 0 0 0 

所以边界框是:

0 0 0 0 0 0 0 
1 1 1 1 1 0 0 
1 0 0 0 1 0 0 
1 0 0 0 1 0 0 
1 1 1 1 1 0 0 
0 0 0 0 0 0 0 
0 0 0 0 0 0 0 

其实在我的任务中,只要知道这个对象的宽高就够了。

一个基本的思路是在场景解析图中从上、下、左、右四个方向搜索四个边。但是图像中可能会有很多小物体,这种方式的时间效率不高。

第二种方法是计算所有非零元素的坐标并找到最大/最小x/y。然后使用这些 x 和 y 计算体重和高度。

还有其他更有效的方法吗?谢谢。

请您参考如下方法:

如果你正在处理图像,你可以使用 scipy 的 ndimage 库。

如果图像中只有一个物体,您可以使用 scipy.ndimage.measurements.find_objects ( http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.ndimage.measurements.find_objects.html ) 获取测量值:

import numpy as np 
from scipy import ndimage 
a = np.array([[0, 0, 0, 0, 0, 0, 0], 
              [0, 1, 1, 0, 0, 0, 0], 
              [1, 1, 1, 1, 0, 0, 0], 
              [0, 0, 1, 1, 1, 0, 0], 
              [0, 0, 1, 1, 1, 0, 0], 
              [0, 0, 0, 0, 0, 0, 0], 
              [0, 0, 0, 0, 0, 0, 0]]) 
 
# Find the location of all objects 
objs = ndimage.find_objects(a) 
 
# Get the height and width 
height = int(objs[0][0].stop - objs[0][0].start) 
width = int(objs[0][1].stop - objs[0][1].start) 

如果图像中有很多物体,首先必须标记每个物体,然后进行测量:

import numpy as np 
from scipy import ndimage 
a = np.array([[0, 0, 0, 0, 0, 0, 0], 
              [0, 1, 1, 0, 0, 0, 0], 
              [1, 1, 1, 1, 0, 0, 0], 
              [0, 0, 1, 1, 1, 0, 0], 
              [0, 0, 1, 1, 1, 0, 0], 
              [0, 0, 0, 0, 0, 0, 0], 
              [0, 0, 1, 1, 1, 0, 0]])  # Second object here 
# Label objects 
labeled_image, num_features = ndimage.label(a) 
# Find the location of all objects 
objs = ndimage.find_objects(labeled_image) 
# Get the height and width 
measurements = [] 
for ob in objs: 
    measurements.append((int(ob[0].stop - ob[0].start), int(ob[1].stop - ob[1].start))) 

如果检查 ndimage.measurements,您可以获得更多测量值:质心、面积...