gpt4 book ai didi

python - Python 中的图像平滑

转载 作者:太空狗 更新时间:2023-10-29 17:00:36 26 4
gpt4 key购买 nike

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

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

最佳答案

好问题! 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()

enter image description here

关于python - Python 中的图像平滑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14765891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com