Convolve2d just by using Numpy

前端 未结 3 737
孤独总比滥情好
孤独总比滥情好 2020-12-02 13:52

I am studying image-processing using Numpy and facing a problem with filtering with convolution.

I would like to convolve a gray-scale image. (convolve a 2d A

3条回答
  •  死守一世寂寞
    2020-12-02 14:03

    You could generate the subarrays using as_strided [1]:

    import numpy as np
    
    a = np.array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24]])
    
    sub_shape = (3,3)
    view_shape = tuple(np.subtract(a.shape, sub_shape) + 1) + sub_shape
    strides = a.strides + a.strides
    
    sub_matrices = np.lib.stride_tricks.as_strided(a,view_shape,strides)
    

    To get rid of your second "ugly" sum, alter your einsum so that the output array only has j and k. This implies your second summation.

    conv_filter = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])
    m = np.einsum('ij,ijkl->kl',conv_filter,sub_matrices)
    
    # [[ 6  7  8]
    #  [11 12 13]
    #  [16 17 18]]
    

提交回复
热议问题