是否有“边界框"?NumPy 中 ndarray 的函数(具有非零值的切片)? [英] Is there a "bounding box" function (slice with non-zero values) for a ndarray in NumPy?

查看:25
本文介绍了是否有“边界框"?NumPy 中 ndarray 的函数(具有非零值的切片)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理通过 numpy.array() 创建的数组,我需要在模拟图像的画布上绘制点.由于包含有意义数据的数组中心部分周围有很多零值,我想修剪"数组,删除只包含零的列和只包含零的行.

I am dealing with arrays created via numpy.array(), and I need to draw points on a canvas simulating an image. Since there is a lot of zero values around the central part of the array which contains the meaningful data, I would like to "trim" the array, erasing columns that only contain zeros and rows that only contain zeros.

所以,我想知道一些原生的 numpy 函数,甚至是一个代码片段来修剪"或找到一个边界框"来只对数组中包含数据的部分进行切片.

So, I would like to know of some native numpy function or even a code snippet to "trim" or find a "bounding box" to slice only the data-containing part of the array.

(因为这是一个概念性的问题,我没有放任何代码,对不起,如果我应该,我很新鲜在 SO 上发帖.)

(since it is a conceptual question, I did not put any code, sorry if I should, I'm very fresh to posting at SO.)

感谢阅读

推荐答案

下面的代码,来自 这个答案在我的测试中运行得最快:

The code below, from this answer runs fastest in my tests:

def bbox2(img):
    rows = np.any(img, axis=1)
    cols = np.any(img, axis=0)
    ymin, ymax = np.where(rows)[0][[0, -1]]
    xmin, xmax = np.where(cols)[0][[0, -1]]
    return img[ymin:ymax+1, xmin:xmax+1]

使用 argwhere 接受的答案有效但运行速度较慢.我的猜测是,这是因为 argwhere 分配了一个巨大的索引输出数组.我在一个大型 2D 阵列(一个 1024 x 1024 的图像,大约有一个 50x100 的非零区域)上进行了测试.

The accepted answer using argwhere worked but ran slower. My guess is, it's because argwhere allocates a giant output array of indices. I tested on a large 2D array (a 1024 x 1024 image, with roughly a 50x100 nonzero region).

这篇关于是否有“边界框"?NumPy 中 ndarray 的函数(具有非零值的切片)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆