是否有一个"边框"功能(切片非零值)在numpy的一个ndarray? [英] Is there a "bounding box" function (slice with non-zero values) for a ndarray in NumPy?

查看:561
本文介绍了是否有一个"边框"功能(切片非零值)在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的功能,甚至是code段,以调整还是找到了边框切片只有数组的包含数据的部分。

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.

(因为它是一个概念性的问题,我没有把任何code,对不起,如果我应该,我很新鲜的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.)

感谢您阅读

推荐答案

这应该这样做:

from numpy import array, argwhere

A = array([[0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 1, 0, 0, 0, 0],
           [0, 0, 1, 1, 0, 0, 0],
           [0, 0, 0, 0, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0]])

B = argwhere(A)
(ystart, xstart), (ystop, xstop) = B.min(0), B.max(0) + 1 
Atrim = A[ystart:ystop, xstart:xstop]

这篇关于是否有一个"边框"功能(切片非零值)在numpy的一个ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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