1. 程式人生 > >二維陣列旋轉90度、180度、270度

二維陣列旋轉90度、180度、270度

      影象處理中,很多時候要使用到二維陣列的旋轉。本質上二維陣列的旋轉其實就是座標的變換,即旋轉後的座標(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;
}