二维数组旋转90度、180度、270度
程序员文章站
2022-05-17 10:05:43
...
图像处理中,很多时候要使用到二维数组的旋转。本质上二维数组的旋转其实就是坐标的变换,即旋转后的坐标(x,y)需要对应到原有二维数组的坐标点上,取到正确的值即可完成正确的旋转。
规则很好找。见如下的代码中的3个转换公式即可。
void Rotate90()
{
int b[2][3] = {{1,2,3},{4,5,6}};
int a[3][2] = {0};
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
{
//a[i][j] = b[h-1-j][i]; here h = 2
a[i][j] = b[2-1-j][i];
}
}
//使用一维数组模拟二维数组
int w = 3;
int h = 2;
int *p = (int *)new int[w*h];
int *p2 = (int *)new int[w*h];
for(int i=0;i<w*h;i++)
{
p[i] = i+1;
}
int newH = w;
int newW = h;
for(int i=0;i<newH;i++)
{
for(int j=0;j<newW;j++)
{
//a[i][j] = b[h-1-j][i]
p2[i*newW+j] = p[(h-1-j)*w+i];
}
}
delete []p;
delete []p2;
}
void Rotate180()
{
int b[2][3] = {{1,2,3},{4,5,6}};
int a[2][3] = {0};
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
//a[i][j] = b[h-1-i][w-1-j]; here h = 2
a[i][j] = b[2-1-i][3-1-j];
}
}
//使用一维数组模拟二维数组
int w = 3;
int h = 2;
int *p = (int *)new int[w*h];
int *p2 = (int *)new int[w*h];
for(int i=0;i<w*h;i++)
{
p[i] = i+1;
}
int newH = h;
int newW = w;
for(int i=0;i<newH;i++)
{
for(int j=0;j<newW;j++)
{
//a[i][j] = b[h-1-i][w-1-j];
p2[i*newW+j] = p[(h-1-i)*w+w-1-j];
}
}
delete []p;
delete []p2;
}
void Rotate270()
{
int b[2][3] = {{1,2,3},{4,5,6}};
int a[3][2] = {0};
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
{
//a[i][j] = b[j][w-1-i]; here w = 3
a[i][j] = b[j][3-1-i];
}
}
//使用一维数组模拟二维数组
int w = 3;
int h = 2;
int *p = (int *)new int[w*h];
int *p2 = (int *)new int[w*h];
for(int i=0;i<w*h;i++)
{
p[i] = i+1;
}
int newH = w;
int newW = h;
for(int i=0;i<newH;i++)
{
for(int j=0;j<newW;j++)
{
//a[i][j] = b[j][w-1-i];
p2[i*newW+j] = p[j*w+w-1-i];
}
}
delete []p;
delete []p2;
}