如何使用python在矩阵中的某个值周围获取框的左上角和右下角坐标?

时间:2011-09-08 11:09:19

标签: python numpy

我有一个2D numpy数组。让我们考虑以下示例

    [[0,6,89,255,1,6,7]
    [0,255,89,255,1,1,7]
    [255,255,255,255,255,255,255]
    [1,2,3,4,5,6,7]
    [1,1,255,5,7,3,255]]

我们需要围绕特定值的框的坐标。例如,对于值255,值255周围的框的坐标将是左上角(0,0)和右下角(4,6)。

如何在python中高效地完成它。

非常感谢。

1 个答案:

答案 0 :(得分:4)

答案非常类似于:Is there a "bounding box" function (slice with non-zero values) for a ndarray in NumPy?

from numpy import array, argwhere

A = array([[0  ,6  ,89 ,255,1  ,6  ,7  ],
           [0  ,255,89 ,255,1  ,1  ,7  ],
           [255,255,255,255,255,255,255],
           [1  ,2  ,3  ,4  ,5  ,6  ,7  ],
           [1  ,1  ,255,5  ,7  ,3  ,255]])

B = argwhere(A==255)
(ystart, xstart), (ystop, xstop) = B.min(0), B.max(0)