Changing structure of numpy array enforcing given value

后端 未结 2 1427
囚心锁ツ
囚心锁ツ 2021-01-28 04:00

How can I downscale the raster data of 4 X 6 size into 2 X 3 size enforcing \'1\' to be chosen if any element with in 2*2 pixels include 1, otherwise 0

2条回答
  •  -上瘾入骨i
    2021-01-28 04:48

    import numpy as np    
    
    def toblocks(arr, nrows, ncols):
        h, w = arr.shape
        blocks = (arr.reshape(h // nrows, nrows, -1, ncols)
                  .swapaxes(1, 2)
                  .reshape(h // nrows, w // ncols, ncols * nrows))
        return blocks    
    
    data = np.array([[0, 0, 1, 1, 0, 0],
                     [1, 0, 0, 1, 0, 0],
                     [1, 0, 1, 0, 0, 0],
                     [1, 1, 0, 0, 0, 0]])
    
    
    blocks = toblocks(data, 2, 2)
    downscaled = blocks.any(axis=-1).astype(blocks.dtype)
    print(downscaled)
    # [[1 1 0]
    #  [1 1 0]]
    

    Where the above solution comes from: A while ago, an SO question asked how to break an array into blocks. All I did was slightly modify that solution to apply any to each of the blocks.

提交回复
热议问题