矩阵旋转(图像旋转)

CareerCup原题:

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rorate the image by 90 degrees. Can you do this in palce?
旋转可以一层一层来旋转。旋转矩阵某个值所在的位置会变,但是所在的层不变。如下图,A在最外层,B在次层。

AAAA

ABBA

ABBA

AAAA

按层循环来旋转每一层。
在旋转某一层时,保存上面的值,把左边的值放到到上面,下面的值放到到左边,右边的值放到到下面,再把保存的上面的值放到右边。依次循环,这样就不许额外空间。 
 

void rotate(int matrix[][N],int n)//传递二维数组,指定第二维维数
{
	for(int layer=0; layer<n/2; layer++)//分层次 
	{
		int first=layer;
		int last=n-1-layer;
		for(int i=first; i<last; i++)//旋转第layer层 
		{
			int offset=i-first; 
			//保存上面的值 
			int top=matrix[first][i];
			//左边转到上面
			matrix[first][i]=matrix[last-offset][first];
			//下面转到左边
			 matrix[last-offset][first]=matrix[last][last-offset];
			 //右边转到下面 
			  matrix[last][last-offset]=matrix[i][last];
			  //上面转到右边 
			  matrix[i][last]=top;
		}
	}
}

测试代码:

#include<iostream>
using namespace std;
#define N 3
int matrix[3][3];
int main()
{
	int k=1;
	for(int i=0; i<N; i++)
		for(int j=0; j<N; j++)
			matrix[i][j]=k++;
	//旋转前 
	cout<<"旋转前"<<endl; 
	for(int i=0; i<N; i++)
	{
		for(int j=0; j<N; j++)
			cout<<matrix[i][j];
		cout<<endl;
	}
	rotate(matrix,N);
	//旋转后 
	cout<<"旋转后"<<endl; 
	for(int i=0; i<N; i++)
	{
		for(int j=0; j<N; j++)
			cout<<matrix[i][j];
		cout<<endl;
	}
		
	return 0;
}



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个matlab代码示例,用于实现图像旋转: ```matlab % 读取原始图像 img = imread('image.jpg'); % 转换成灰度图像 gray_img = rgb2gray(img); % 定义旋转角度 theta = 30; % 计算旋转矩阵 rot_mat = [cosd(theta) -sind(theta) 0; sind(theta) cosd(theta) 0; 0 0 1]; % 计算新图像大小 [height, width] = size(gray_img); new_height = ceil(height * abs(cosd(theta)) + width * abs(sind(theta))); new_width = ceil(width * abs(cosd(theta)) + height * abs(sind(theta))); new_gray_img = zeros(new_height, new_width, 'uint8'); % 计算中心点 center = [height/2, width/2]; % 遍历新图像的每个像素,并计算对应原始图像的坐标 for i = 1:new_height for j = 1:new_width % 计算对应原始图像的坐标 pos = rot_mat \ [i-center(1), j-center(2), 1]'; x = round(pos(1)) + center(1); y = round(pos(2)) + center(2); % 判断是否越界 if x >= 1 && x <= height && y >= 1 && y <= width new_gray_img(i, j) = gray_img(x, y); end end end % 显示结果 figure; subplot(1,2,1); imshow(gray_img); title('原始图像'); subplot(1,2,2); imshow(new_gray_img); title('旋转后的图像'); ``` 该代码读取一张原始图像,并将其转换成灰度图像。然后,定义旋转角度,并计算旋转矩阵。接下来,计算新图像的大小,并创建一个新的灰度图像作为旋转后的图像。然后,遍历新图像的每个像素,并计算对应原始图像的坐标。最后,将对应像素的灰度值赋值给新图像,并显示结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值