Image smoothing in Python

前端 未结 3 1038
慢半拍i
慢半拍i 2020-12-28 08:09

I wanted to try to write a simple function to smooth an inputted image. I was trying to do this using the Image and numpy libraries. I was thinking that using a convolution

3条回答
  •  遥遥无期
    2020-12-28 08:49

    You want to look at ndimage, which is a module in scipy. It has a number of filters all set up as functions, and nice wrappers for convolving arbitrary kernels.

    For example,

    img_gaus = ndimage.filters.gaussian_filter(img, 2, mode='nearest')
    

    convolves your image with a guassian with sigma of 2.

    If you want to convolve an arbitrary kernel, say a cross

    k = np.array([[0, 1, 0],
                  [1, 1, 1],
                  [0, 1, 0]])
    
    img2 = ndimage.convolve(img, k, mode='constant')
    

    These functions are also good for higher dimensions, so you could use almost identical code (just scaling up the dimension of your kernel) to smooth data in higher dimensions.

    The mode and cval parameters control how the convolutions deals with pixels at the edge of your image (for a pixel on the edge, half of the area that the kernel needs to look at does not exist, so you need to pick something to pad your image out with).

提交回复
热议问题