Is there a “bounding box” function (slice with non-zero values) for a ndarray in NumPy?

后端 未结 3 850
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 11:06

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

3条回答
  •  被撕碎了的回忆
    2020-12-10 11:30

    This should do it:

    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]
    

提交回复
热议问题