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

标签 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 中高效地完成此操作。

非常感谢。

最佳答案

答案非常类似于: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/

相关文章:

python - SWIG:如何将 python 文件合并到 swig 生成的最终模块文件中

python - 从 __init__.py 导入方法

python - 磁盘读取会减慢 MySQL 中的 INSERT 速度

Python-获取图像的白色像素

python - 展开 Numpy "object"dtypes

performance - 加速结构化 NumPy 数组

python - 从 CSV 文件创建矩阵

javascript - 表单集表单域中的键盘错误

python - 多次克隆一个 NumPy 数组

python - 为什么字典查找总是比列表查找好?