在图像处理中,有的需要将图像进行Z字形编码,编码规则如下图:
1 | 3 | 4 |
2 | 5 | 8 |
6 | 7 | 9 |
即按1 2 3 4 5 6 7 8 9的顺序排列矩阵中的元素。
逆编码是将变换后的矩阵还原。
本文用MATLAB实现了Z字形编码和逆编码。
%% 按Z字形编码
function [B]=zTransform(A)
sizeA=size(A);
B=zeros(sizeA(1),sizeA(2));
i=1;
j=1;
B(i,j)=A(i,j);
i=i+1;
index=0;
tag=1;
while (i+j)<=(sizeA(1)+sizeA(2))&&i<=sizeA(1)&&j<=sizeA(2)
if i==sizeA(1)&&j==sizeA(2)
index=index+1;
B(fix(index/sizeA(2))+1,mod(index,sizeA(2))+1)=A(i,j);
break;
end
if tag==1
while i<=sizeA(1)&&j<=sizeA(2)&&i>=1&&j>=1
index=index+1;
B(fix(index/sizeA(2))+1,mod(index,sizeA(2))+1)=A(i,j);
i=i-1;
j=j+1;
end
i=i+1;
j=j-1;
if j<sizeA(2)
j=j+1;
else
i=i+1;
end
tag=0;
else if tag==0
while i<=sizeA(1)&&j<=sizeA(2)&&i>=1&&j>=1
index=index+1;
B(fix(index/sizeA(2))+1,mod(index,sizeA(2))+1)=A(i,j);
i=i+1;
j=j-1;
end
i=i-1;
j=j+1;
if i<sizeA(1)
i=i+1;
else
j=j+1;
end
tag=1;
end
end
end
end
%% 按Z字形逆变换
function [B]=iZTransform(A)
sizeA=size(A);
B=zeros(sizeA(1),sizeA(2));
i=1;
j=1;
B(i,j)=A(i,j);
i=i+1;
index=0;
tag=1;
while (i+j)<=(sizeA(1)+sizeA(2))&&i<=sizeA(1)&&j<=sizeA(2)
if i==sizeA(1)&&j==sizeA(2)
index=index+1;
%B(fix(index/sizeA(2))+1,mod(index,sizeA(2))+1)=A(i,j);
B(i,j)=A(fix(index/sizeA(2))+1,mod(index,sizeA(2))+1);
break;
end
if tag==1
while i<=sizeA(1)&&j<=sizeA(2)&&i>=1&&j>=1
index=index+1;
%B(fix(index/sizeA(2))+1,mod(index,sizeA(2))+1)=A(i,j);
B(i,j)=A(fix(index/sizeA(2))+1,mod(index,sizeA(2))+1);
i=i-1;
j=j+1;
end
i=i+1;
j=j-1;
if j<sizeA(2)
j=j+1;
else
i=i+1;
end
tag=0;
else if tag==0
while i<=sizeA(1)&&j<=sizeA(2)&&i>=1&&j>=1
index=index+1;
%B(fix(index/sizeA(2))+1,mod(index,sizeA(2))+1)=A(i,j);
B(i,j)=A(fix(index/sizeA(2))+1,mod(index,sizeA(2))+1);
i=i+1;
j=j-1;
end
i=i-1;
j=j+1;
if i<sizeA(1)
i=i+1;
else
j=j+1;
end
tag=1;
end
end
end
end
例子:
A =
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
B=zTransform(A)
B =
1 4 2
3 5 7
10 8 6
9 11 13
16 14 12
15 17 18
C=iZTransform(B)
C =
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18