Sobel filter kernel of large size

后端 未结 9 781
渐次进展
渐次进展 2020-12-02 08:38

I am using a sobel filter of size 3x3 to calculate the image derivative. Looking at some articles on the internet, it seems that kernels for sobel filter for size 5x5 and 7x

9条回答
  •  渐次进展
    2020-12-02 09:10

    Here is a simple solution made with python 3 using numpy and the @Daniel answer.

    def custom_sobel(shape, axis):
        """
        shape must be odd: eg. (5,5)
        axis is the direction, with 0 to positive x and 1 to positive y
        """
        k = np.zeros(shape)
        p = [(j,i) for j in range(shape[0]) 
               for i in range(shape[1]) 
               if not (i == (shape[1] -1)/2. and j == (shape[0] -1)/2.)]
    
        for j, i in p:
            j_ = int(j - (shape[0] -1)/2.)
            i_ = int(i - (shape[1] -1)/2.)
            k[j,i] = (i_ if axis==0 else j_)/float(i_*i_ + j_*j_)
        return k
    

    It returns the kernel (5,5) like this:

    Sobel x:
       [[-0.25 -0.2   0.    0.2   0.25]
        [-0.4  -0.5   0.    0.5   0.4 ]
        [-0.5  -1.    0.    1.    0.5 ]
        [-0.4  -0.5   0.    0.5   0.4 ]
        [-0.25 -0.2   0.    0.2   0.25]]
    
    
    Sobel y:
       [[-0.25 -0.4  -0.5  -0.4  -0.25]
        [-0.2  -0.5  -1.   -0.5  -0.2 ]
        [ 0.    0.    0.    0.    0.  ]
        [ 0.2   0.5   1.    0.5   0.2 ]
        [ 0.25  0.4   0.5   0.4   0.25]]
    

    If anyone know a better way to do that in python, please let me know. I'm a newbie yet ;)

提交回复
热议问题