陟览数
4,333
经过学习和探索,掌握了一维卷积和二维卷积矩阵乘法的实现。
对于一维向量的卷积,Matlab提供了对应于convmtx计算向量的乘法矩阵。 这是Toeplitz矩阵。
% By TomHeaven,Hanlin _ tan @ nudt.edu.cn @ 2016.09.28
x=[1 2 3] ';
y=[4(5) );
n=length(y;
h=convMTX(x,n );
z=H*y;
z_c=conv(x,y );
DIFF=norm(z-z_c ) )
% By TomHeaven,Hanlin _ tan @ nudt.edu.cn @ 2016.09.28
x=[1 2 3] ';
y=[4(5) );
n=length(y;
h=convMTX(x,n );
z=H*y;
z_c=conv(x,y );
DIFF=norm(z-z_c ) )
二维卷积(图像和核卷积)的矩阵乘法形式可以通过简单的运算处理导出矩阵的构造方法。 这是带宽矩阵。
设二维图像矩阵为$X in R^{m times n}$,卷积核矩阵为$Y in R^{p times p}$。 将这些按行优先展开得到的向量分别为$x,y$。
令
$$
X=left[
begin{matrix}
1345(5) )
68910 () )
11 12 13 14 15
end{matrix}
right]
$$
$$
Y=left[
begin{matrix}
1333
46(6) )
7 8 9
end{matrix}
right]
$$
然后,将$Z=X * Y$,$z$作为$z$,逐行优先展开得到的向量。
可以构筑矩阵
$$
H=left[
begin{matrix}
970065403100\
087006540310\
098700650031\
end{matrix}
right]
$$
就这样
$$
Hx=z
$$
上面的例子已经包含了$H$的结构定律:
1. $H$的大小为$m times {pn}$。
2 .第一行分为$k$组,每组分为$m$个元素。 $i$组中前$k$个元素为$Y$的$p-i 1$行元素按相反顺序排列,剩下的$n-p$个元素为0。
3 .第i1行比第I行向右移动一个位置,末尾的要素(0)被补充在行的开头。
用Matlab实现是
% By TomHeaven,Hanlin _ tan @ nudt.edu.cn @ 2016.09.28
x=(1:24 );
y=(1:9 );
x=reshape(x,[4]6) ';
y=reshape(y,[3] ) '; % square kernel
% constructconvolutionalmultiplicationmatrixh
y_hat=[fliplr(flipud(y ) ]Zeros ) size(X(y,1 ),size ) x,2 )-size (y,2 ) ];
y_hat=reshape(y_hat ',[1,size(y_hat,1 ) size(y_hat,2 ) ];
y_hat=[y_hatzeros(1,) size(x,1 )-size (y,1 ) ] * size (x,2 ) ];
h=Zeros () size ) x,1 )-size ) y,1 )1) * ) size ) x,2 )-size ) y,2 )1),length(x ) ) x );
% h (1, )=y_hat;
len=length(y_hat );
cnt=0;
forI=1:size(x,1 )- size(Y ) y,1 ) 1
forj=1:size(x,2 )- size(Y ) y,2 ) 1
cnt=cnt 1;
h(CNT, )=y_hat;
y_hat(2:len )=y _ hat (1: len-1 );
y_hat(1)=0;
结束
% skip invalid convolution
forj=1:size(x,2 )-(size ) x,2 )- size(Y ) y,2 )1) ) ) ) ) ) ) ) )。
y_hat(2:len )=y _ hat (1: len-1 );
y_hat(1)=0;
结束
结束
z=H * x;
z=reshape(z ),[(size(X(x,2 )-size (y,2 )1),(size ) x,1 )-size (y,1 ) ) ] );
z=conV2(x,y,' valid ' );
DIFF=NORM(z-z ) )
% By TomHeaven,Hanlin _ tan @ nudt.edu.cn @ 2016.09.28
x=(1:24 );
y=(1:9 );
x=reshape(x,[4]6) ';
y=reshape(y,[3] ) '; % square kernel
% constructconvolutionalmultiplicationmatrixh
y_hat=[fliplr(flipud(y ) ]Zeros ) size(X(y,1 ),size ) x,2 )-size (y,2 ) ];
y_hat=reshape(y_hat ',[1,size(y_hat,1 ) size(y_hat,2 ) ];
y_hat=[y_hatzeros(1,) size(x,1 )-size (y,1 ) ] * size (x,2 ) ];
h=Zeros () size ) x,1 )-size ) y,1 )1) * ) size ) x,2 )-size ) y,2 )1),length(x ) ) x );
% h (1, )=y_hat;
len=length(y_hat );
cnt=0;
forI=1:size(x,1 )- size(Y ) y,1 ) 1
forj=1:size(x,2 )- size(Y ) y,2 ) 1
cnt=cnt 1;
h(CNT, )=y_hat;
y_hat(2:len )=y _ hat (1: len-1 );
y_hat(1)=0;
结束
% skip invalid convolution
forj=1:size(x,2 )-(size ) x,2 )- size(Y ) y,2 )1) ) ) ) ) ) ) ) )。
y_hat(2:len )=y _ hat (1: len-1 );
y_hat(1)=0;
结束
结束
z=H * x;
z=reshape(z ),[(size(X(x,2 )-size (y,2 )1),(size ) x,1 )-size (y,1 ) ) ] );
z=conV2(x,y,' valid ' );
DIFF=NORM(z-z ) )