Pixel neighbors in 2d array (image) using Python

后端 未结 7 994
灰色年华
灰色年华 2020-12-01 08:40

I have a numpy array like this:

x = np.array([[1,2,3],[4,5,6],[7,8,9]])

I need to create a function let\'s call it \"neighbors\" with the f

7条回答
  •  猫巷女王i
    2020-12-01 09:05

    Have a look at scipy.ndimage.generic_filter.

    As an example:

    import numpy as np
    import scipy.ndimage as ndimage
    
    def test_func(values):
        print values
        return values.sum()
    
    
    x = np.array([[1,2,3],[4,5,6],[7,8,9]])
    
    footprint = np.array([[1,1,1],
                          [1,0,1],
                          [1,1,1]])
    
    results = ndimage.generic_filter(x, test_func, footprint=footprint)
    

    By default, it will "reflect" the values at the boundaries. You can control this with the mode keyword argument.

    However, if you're wanting to do something like this, there's a good chance that you can express your problem as a convolution of some sort. If so, it will be much faster to break it down into convolutional steps and use more optimized functions (e.g. most of scipy.ndimage).

提交回复
热议问题