Python中的图像平滑

Nic*_*ick 15 python numpy image-processing smoothing

我想尝试编写一个简单的函数来平滑输入的图像.我试图使用Image和numpy库来做到这一点.我在想使用卷积掩码是解决这个问题的方法,我知道numpy有一个内置的卷积函数.

如何使用numpy.convolve来平滑图像?

tac*_*ell 17

你想看看ndimage,这是一个模块scipy.它有许多过滤器都设置为函数,以及用于卷积任意内核的漂亮包装器.

例如,

img_gaus = ndimage.filters.gaussian_filter(img, 2, mode='nearest')
Run Code Online (Sandbox Code Playgroud)

用2的sigma guassian卷曲你的形象.

如果你想卷积任意内核,请说一个十字架

k = np.array([[0, 1, 0],
              [1, 1, 1],
              [0, 1, 0]])

img2 = ndimage.convolve(img, k, mode='constant')
Run Code Online (Sandbox Code Playgroud)

这些函数也适用于更高的维度,因此您可以使用几乎相同的代码(只是扩展内核的维度)来平滑更高维度的数据.

modecval参数控制与像素的回旋交易在图像的边缘(上边缘的像素,该面积的一半,内核需要看不存在,所以你需要捡东西垫你的形象了用).


wim*_*wim 17

好问题! tcaswell帖子在这里是一个很好的建议,但你不会这么学习,因为scipy正在为你做所有的工作!既然你的问题说你想尝试编写这个函数,我会告诉你更粗略和基本的方法来手动完成这一切,希望你能更好地理解卷积等数学,然后你就可以改进它有你自己的想法和努力!

注意:你会得到不同形状/大小的内核的不同结果,高斯是常用的方法,但你可以尝试其他一些有趣(余弦,三角等!).我刚刚在现场制作了这个,我觉得它是一种金字塔形状.

import scipy.signal
import numpy as np
import matplotlib.pyplot as plt

im = plt.imread('example.jpg')
im /= 255.   # normalise to 0-1, it's easier to work in float space

# make some kind of kernel, there are many ways to do this...
t = 1 - np.abs(np.linspace(-1, 1, 21))
kernel = t.reshape(21, 1) * t.reshape(1, 21)
kernel /= kernel.sum()   # kernel should sum to 1!  :) 

# convolve 2d the kernel with each channel
r = scipy.signal.convolve2d(im[:,:,0], kernel, mode='same')
g = scipy.signal.convolve2d(im[:,:,1], kernel, mode='same')
b = scipy.signal.convolve2d(im[:,:,2], kernel, mode='same')

# stack the channels back into a 8-bit colour depth image and plot it
im_out = np.dstack([r, g, b])
im_out = (im_out * 255).astype(np.uint8) 

plt.subplot(2,1,1)
plt.imshow(im)
plt.subplot(2,1,2)
plt.imshow(im_out)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述