本文的目的是使用自定義的卷積核對圖片進(jìn)行卷積操作。pytorch封裝在torch.nn里的Conv2d非常好用两踏,然而其卷積核的權(quán)重都是需要學(xué)習(xí)的參數(shù),如果想要自定義一個卷積核(比如Gabor核)來提取圖像特征,conv2d就不適用了秸架。目前有兩個解決方案:
方案一 使用opencv
這是我最初采用的方案,使用opencv自帶的getGaborKernel()函數(shù)來得到gabor kernel咆蒿,然后在圖像上運用filter2D()函數(shù)提取gabor特征:
# 得到卷積核
kernel_size = 7
theta = np.pi / 2
lamda = np.pi / 2
kernel = cv2.getGaborKernel((kernel_size, kernel_size), 1.0,\
theta, lamda, 0.5, 0, ktype=cv2.CV_32F)
# 進(jìn)行濾波
ac = np.zeros_like(im)
gabor_feature = cv2.filter2/d(img, cv2.CV_8UC3, kern)
np.maximum(ac, gabor_feature, gabor_feature)
這里可以多設(shè)幾組參數(shù)东抹,進(jìn)行多次濾波。
方案二 使用pytorch自帶卷積核
opencv雖然強(qiáng)大沃测,但是有兩個問題缭黔。第一,它需要輸入ndarray蒂破,輸出也是ndarray馏谨,在訓(xùn)練中在線生成gabor feature時需要進(jìn)行數(shù)據(jù)格式轉(zhuǎn)換等操作,時間代價很長附迷,而且操作也不方便惧互;第二,如果想要將filter的參數(shù)當(dāng)成可學(xué)習(xí)參數(shù)喇伯,opencv就不能使用了喊儡,除非你還想自己寫一個backward層。所以稻据,我還是使用了pytorch自帶的卷積操作:torch.nn.functional.conv2d()
這個卷積核與nn.Conv2d不同艾猜,它的weight可以自己設(shè)定。好處是捻悯,你既可以把各項參數(shù)寫死在里面箩朴,不讓它求導(dǎo),也可以當(dāng)成可學(xué)習(xí)參數(shù)秋度,反向傳播有pytorch來自動實現(xiàn)炸庞;并且,由于這是pytorch自帶的荚斯,在訓(xùn)練中也不需要我們?nèi)タ紤]batch維度埠居,數(shù)據(jù)格式采用torch tensor,方便得很事期。還有一個好處是滥壕,它可以像普通cnn的卷積核一樣操作,有4個維度兽泣,分別是輸出通道绎橘,輸入通道,卷積核高,卷積核寬称鳞,這樣可以很方便地把自定義的卷積核寫成一個卷積層涮较。具體操作:
import torch.nn.functional as F
import torch
def gabor_fn(kernel_size, channel_in, channel_out, sigma, theta, Lambda, psi, gamma):
sigma_x = sigma # [channel_out]
sigma_y = sigma.float() / gamma # element-wize division, [channel_out]
# Bounding box
nstds = 3 # Number of standard deviation sigma
xmax = kernel_size // 2
ymax = kernel_size // 2
xmin = -xmax
ymin = -ymax
ksize = xmax - xmin + 1
y_0 = torch.arange(ymin, ymax+1)
y = y_0.view(1, -1).repeat(channel_out, channel_in, ksize, 1).float()
x_0 = torch.arange(xmin, xmax+1)
x = x_0.view(-1, 1).repeat(channel_out, channel_in, 1, ksize).float() # [channel_out, channelin, kernel, kernel]
# Rotation
# don't need to expand, use broadcasting, [64, 1, 1, 1] + [64, 3, 7, 7]
x_theta = x * torch.cos(theta.view(-1, 1, 1, 1)) + y * torch.sin(theta.view(-1, 1, 1, 1))
y_theta = -x * torch.sin(theta.view(-1, 1, 1, 1)) + y * torch.cos(theta.view(-1, 1, 1, 1))
# [channel_out, channel_in, kernel, kernel]
gb = torch.exp(-.5 * (x_theta ** 2 / sigma_x.view(-1, 1, 1, 1) ** 2 + y_theta ** 2 / sigma_y.view(-1, 1, 1, 1) ** 2)) \
* torch.cos(2 * math.pi / Lambda.view(-1, 1, 1, 1) * x_theta + psi.view(-1, 1, 1, 1))
return gb
class GaborConv2d(nn.Module):
def __init__(self, channel_in, channel_out, kernel_size, stride=1, padding=0):
super(GaborConv2d, self).__init__()
self.kernel_size = kernel_size
self.channel_in = channel_in
self.channel_out = channel_out
self.stride = stride
self.padding = padding
self.Lambda = nn.Parameter(torch.rand(channel_out), requires_grad=True)
self.theta = nn.Parameter(torch.randn(channel_out) * 1.0, requires_grad=True)
self.psi = nn.Parameter(torch.randn(channel_out) * 0.02, requires_grad=True)
self.sigma = nn.Parameter(torch.randn(channel_out) * 1.0, requires_grad=True)
self.gamma = nn.Parameter(torch.randn(channel_out) * 0.0, requires_grad=True)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
theta = self.sigmoid(self.theta) * math.pi * 2.0
gamma = 1.0 + (self.gamma * 0.5)
sigma = 0.1 + (self.sigmoid(self.sigma) * 0.4)
Lambda = 0.001 + (self.sigmoid(self.Lambda) * 0.999)
psi = self.psi
kernel = gabor_fn(self.kernel_size, self.channel_in, self.channel_out, sigma, theta, Lambda, psi, gamma)
kernel = kernel.float() # [channel_out, channel_in, kernel, kernel]
out = F.conv2d(x, kernel, stride=self.stride, padding=self.padding)
return out
我在這里把gabor操作寫成了一個層,即GaborConv2d冈止,可以輸入卷積核大小狂票,輸入及輸出通道,步長以及padding熙暴,跟普通卷積相同闺属。lambda、sigma等參數(shù)是可學(xué)習(xí)的周霉,卷積核權(quán)重是用gabor_fn根據(jù)可學(xué)習(xí)參數(shù)得到的掂器,其大小為[channel_out, channel_in, ksize, ksize]。調(diào)用這個層可以像調(diào)用其他普通卷積一樣俱箱,很容易加到網(wǎng)絡(luò)中唉匾。