How to obtain a gaussian filter in python

后端 未结 8 1369
广开言路
广开言路 2021-01-31 03:57

I am using python to create a gaussian filter of size 5x5. I saw this post here where they talk about a similar thing but I didn\'t find the exact way to get equivalent python c

8条回答
  •  温柔的废话
    2021-01-31 04:18

    here is to provide an nd-gaussian window generator:

    def gen_gaussian_kernel(shape, mean, var):
        coors = [range(shape[d]) for d in range(len(shape))]
        k = np.zeros(shape=shape)
        cartesian_product = [[]]
        for coor in coors:
            cartesian_product = [x + [y] for x in cartesian_product for y in coor]
        for c in cartesian_product:
            s = 0
            for cc, m in zip(c,mean):
                s += (cc - m)**2
            k[tuple(c)] = np.exp(-s/(2*var))
        return k
    

    this function will give you an unnormalized gaussian windows with given shape, center, and variance. for instance: gen_gaussian_kernel(shape=(3,3,3),mean=(1,1,1),var=1.0) output->

    [[[ 0.22313016  0.36787944  0.22313016]
      [ 0.36787944  0.60653066  0.36787944]
      [ 0.22313016  0.36787944  0.22313016]]
    
     [[ 0.36787944  0.60653066  0.36787944]
      [ 0.60653066  1.          0.60653066]
      [ 0.36787944  0.60653066  0.36787944]]
    
     [[ 0.22313016  0.36787944  0.22313016]
      [ 0.36787944  0.60653066  0.36787944]
      [ 0.22313016  0.36787944  0.22313016]]]
    

提交回复
热议问题