gpt4 book ai didi

python - PyTorch 中的高斯滤波器

转载 作者:行者123 更新时间:2023-12-04 13:15:55 27 4
gpt4 key购买 nike

我正在寻找一种仅使用 PyTorch 函数将高斯滤波器应用于图像(张量)的方法。使用numpy,等价的代码是

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

# Define 2D Gaussian kernel
def gkern(kernlen=256, std=128):
"""Returns a 2D Gaussian kernel array."""
gkern1d = signal.gaussian(kernlen, std=std).reshape(kernlen, 1)
gkern2d = np.outer(gkern1d, gkern1d)
return gkern2d

# Generate random matrix and multiply the kernel by it
A = np.random.rand(256*256).reshape([256,256])

# Test plot
plt.figure()
plt.imshow(A*gkern(256, std=32))
plt.show()

我发现的最接近的建议是基于 this post :
import torch.nn as nn

conv = nn.Conv2d(in_channels = 1, out_channels = 1, kernel_size=264, bias=False)
with torch.no_grad():
conv.weight = gaussian_weights

但它给了我错误 NameError: name 'gaussian_weights' is not defined .我怎样才能让它工作?

最佳答案

Yupp I also had the same idea. So now the question becomes: is there a way to define a Gaussian kernel (or a 2D Gaussian) without using Numpy and/or explicitly specifying the weights?


是的,这很容易。看看 signal.gaussian的函数文档就知道了.有一个链接到 source code .所以该方法正在做的是以下内容:
def gaussian(M, std, sym=True):
if M < 1:
return np.array([])
if M == 1:
return np.ones(1, 'd')
odd = M % 2
if not sym and not odd:
M = M + 1
n = np.arange(0, M) - (M - 1.0) / 2.0
sig2 = 2 * std * std
w = np.exp(-n ** 2 / sig2)
if not sym and not odd:
w = w[:-1]
return w
你很幸运,因为在 Pytorch 中转换很简单,(几乎)只是替换 np来自 torch你就完成了!
另外,请注意 np.outer火炬中的等效项是 ger .

关于python - PyTorch 中的高斯滤波器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60534909/

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