Python中的图像平滑 [英] Image smoothing in Python

查看:493
本文介绍了Python中的图像平滑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 mask would be an approach to this problem and I know numpy has a convolve function build in.

我怎样才能使用numpy.convolve 以平滑图像?

How can I use the numpy.convolve to smooth an image?

推荐答案

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

Nice question! tcaswell post here is a great suggestion, but you will not learn much this way because scipy is doing all the work for you! Since your question said you wanted to try and write the function, I will show you a bit more crude and basic kind of way to do it all manually in the hope that you will better understand the maths behind convolution etc, and then you can improve it with your own ideas and efforts!

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

Note: You will get different results with different shapes/sizes of kernels, a Gaussian is the usual way but you can try out some other ones for fun (cosine, triangle, etc!). I just made up this one on the spot, I think it's a kind of pyramid shaped one.

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()

这篇关于Python中的图像平滑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆