Applying the Sobel filter using scipy

前端 未结 3 873
刺人心
刺人心 2021-02-04 11:53

I\'m trying to apply the Sobel filter on an image to detect edges using scipy. I\'m using Python 3.2 (64 bit) and scipy 0.9.0 on Windows 7 Ultimate (64 bit). Currently my code i

3条回答
  •  孤街浪徒
    2021-02-04 12:39

    or you can use :

    def sobel_filter(im, k_size):
    
        im = im.astype(np.float)
        width, height, c = im.shape
        if c > 1:
            img = 0.2126 * im[:,:,0] + 0.7152 * im[:,:,1] + 0.0722 * im[:,:,2]
        else:
            img = im
    
        assert(k_size == 3 or k_size == 5);
    
        if k_size == 3:
            kh = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype = np.float)
            kv = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], dtype = np.float)
        else:
            kh = np.array([[-1, -2, 0, 2, 1], 
                       [-4, -8, 0, 8, 4], 
                       [-6, -12, 0, 12, 6],
                       [-4, -8, 0, 8, 4],
                       [-1, -2, 0, 2, 1]], dtype = np.float)
            kv = np.array([[1, 4, 6, 4, 1], 
                       [2, 8, 12, 8, 2],
                       [0, 0, 0, 0, 0], 
                       [-2, -8, -12, -8, -2],
                       [-1, -4, -6, -4, -1]], dtype = np.float)
    
        gx = signal.convolve2d(img, kh, mode='same', boundary = 'symm', fillvalue=0)
        gy = signal.convolve2d(img, kv, mode='same', boundary = 'symm', fillvalue=0)
    
        g = np.sqrt(gx * gx + gy * gy)
        g *= 255.0 / np.max(g)
    
        #plt.figure()
        #plt.imshow(g, cmap=plt.cm.gray)      
    
        return g
    

    for more see here

提交回复
热议问题