我有一个 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 中高效地完成此操作。
非常感谢。
最佳答案
答案非常类似于: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)
关于python - 如何使用python获取矩阵中某个值周围的框的左上角和右下角坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7347101/