OpenVG中可以使用投影变换(本例中为仿射变换)来实现图像的变形效果,进而可以用于纹理映射。
为简单起见只考虑三角形到三角形的映射。
变换矩阵T为:
|sx shx tx|
|shy sy ty|
|0 0 1 |
其中sx,sy表示伸缩,shx,shy表示变形,tx,ty表示位移。
设纹理图像中的坐标为(u,v),目标区域中的坐标表示为(x,y),则纹理映射即是从纹理图像到目标区域坐标的转换:
(x y 1)'=T*(u v 1)' (1)
其中
u=(tx1 tx2 1),v=(ty1 ty2 1)表示纹理图像的三个顶点坐标
x=(x1 x2 1), y=(y1 y2 1)表示目标区域的三个顶点坐标
我们需要把变换矩阵T求出来。为简洁起见,(1)式简写为
B=T*A
则 T=B*inv(A)
而inv(A)=A*/|A|
其中inv(A)表示A的逆矩阵
A*表示A的伴随矩阵
|A|表示A的行列式
//求变换矩阵T的代码
void vg_GetTexTransMatrix(short x1, short y1, short x2, short y2, short x3, short y3,
short tx1, short ty1, short tx2, short ty2, short tx3, short ty3)
{
//求行列式|A|
int detA;
detA = tx1*ty2 + tx2*ty3 + tx3*ty1 - tx3*ty2 - tx1*ty3 - tx2*ty1;
// 求伴随矩阵A*
int A11,A12,A13,A21,A22,A23,A31,A32,A33;
A11 = ty2 - ty3;
A21 = -(ty1 - ty3);
A31 = ty1 - ty2;
A12 = -(tx2 - tx3);
A22 = tx1 - tx3;
A32 = -(tx1 - tx2);
A13 = tx2*ty3 - tx3*ty2;
A23 = -(tx1*ty3 - tx3*ty1);
A33 = tx1*ty2 - tx2*ty1;
//求变换矩阵T
float texMatrix[9]={0};
texMatrix[0] = (x1*A11 + x2*A21 + x3*A31)/detA;//t11
texMatrix[1] = (y1*A11 + y2*A21 + y3*A31)/detA;//t21
texMatrix[2] = ( A11 + A21 + A31)/detA;//t31
texMatrix[3] = (x1*A12 + x2*A22 + x3*A32)/detA;//t12
texMatrix[4] = (y1*A12 + y2*A22 + y3*A32)/detA;//t22
texMatrix[5] = ( A12 + A22 + A32)/detA;//t32
texMatrix[6] = (x1*A13 + x2*A23 + x3*A33)/detA;//t13
texMatrix[7] = (y1*A13 + y2*A23 + y3*A33)/detA;//t23
texMatrix[8] = ( A13 + A23 + A33)/detA;//t33
}
PS:仿射变换与投影变换都会将直线映射为直线,但仿射变换把直线上等距分布的点映射为等距分布的点,投影变换则不一定(Both affine and projective transformations map straight lines to straight lines. However, affine transformations map evenly spaced points along a source line to evenly spaced points in the destination, whereas...)。当为仿射变换时,数学上表现为变换矩阵中的齐次项[w0,w1,w2]等于[0 0 1]。