图像旋转之以原点为中心

原理见图:




代码如下:

void Ctry::OnTryTyr1()
{
	 //TODO:  在此添加命令处理程序代码
	IplImage *img = cvLoadImage("C:\\Users\\Administrator\\Desktop\\3838.jpg");
	IplImage *dst = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 3);
	int i, j;     //目标图像坐标
	int u, v;   //源图像坐标
	int ang = 30;   //旋转角度
	CvScalar pixel;
	for (i = 0; i < dst->width; i++)
	{	
		for ( j = 0; j < dst->height; j++)
		{
			u = int(i*cos(ang*PI / 180) + j*sin(ang*PI / 180) + 0.5);
			v = int(j*cos(ang*PI / 180) - i*sin(ang*PI / 180) + 0.5);
			if ((u < img->width)&&(v < img->height)&&(u >= 0) && (v >= 0))
			{
				pixel = cvGet2D(img, v, u);
				cvSet2D(dst, j, i, pixel);
			}
			else
			{
				cvSet2D(dst, j, i, RGB(0,0,0));
			}
		}
	}
	cvSaveImage("C:\\Users\\Administrator\\Desktop\\dst.jpg",dst);
	cvNamedWindow(" dst", CV_WINDOW_AUTOSIZE);
	cvShowImage(" dst", dst);
	cvNamedWindow("img", CV_WINDOW_AUTOSIZE);
	cvShowImage("img", img);
	cvWaitKey(0);

	cvReleaseImage(&img);
	cvReleaseImage(&dst);
	cvDestroyWindow(" dst");
	cvDestroyWindow("img");
}

效果如图:

    


可以使用Matlab中的imrotate函数实现图像的旋转。具体步骤如下: 1. 读取图像 ```matlab img = imread('example.jpg'); ``` 2. 计算旋转角度的弧度值 ```matlab theta = 5 * pi / 180; % 将角度转换为弧度 ``` 3. 计算旋转后的图像大小 ```matlab [h, w] = size(img); newH = round(h * abs(cos(theta)) + w * abs(sin(theta))); newW = round(w * abs(cos(theta)) + h * abs(sin(theta))); ``` 4. 计算旋转后的图像中心坐标 ```matlab cx = (w + 1) / 2; cy = (h + 1) / 2; newCx = (newW + 1) / 2; newCy = (newH + 1) / 2; ``` 5. 生成旋转矩阵 ```matlab T = [cos(theta) sin(theta) 0; -sin(theta) cos(theta) 0; (1 - cos(theta)) * newCx + sin(theta) * newCy - cx, (1 - cos(theta)) * newCy - sin(theta) * newCx - cy, 1]; ``` 6. 进行图像旋转 ```matlab rotatedImg = imwarp(img, affine2d(T), 'OutputView', imref2d([newH, newW], [-newCx, newCx], [-newCy, newCy])); ``` 7. 显示旋转后的图像 ```matlab imshow(rotatedImg); ``` 完整的Matlab程序如下: ```matlab img = imread('example.jpg'); theta = 5 * pi / 180; [h, w] = size(img); newH = round(h * abs(cos(theta)) + w * abs(sin(theta))); newW = round(w * abs(cos(theta)) + h * abs(sin(theta))); cx = (w + 1) / 2; cy = (h + 1) / 2; newCx = (newW + 1) / 2; newCy = (newH + 1) / 2; T = [cos(theta) sin(theta) 0; -sin(theta) cos(theta) 0; (1 - cos(theta)) * newCx + sin(theta) * newCy - cx, (1 - cos(theta)) * newCy - sin(theta) * newCx - cy, 1]; rotatedImg = imwarp(img, affine2d(T), 'OutputView', imref2d([newH, newW], [-newCx, newCx], [-newCy, newCy])); imshow(rotatedImg); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值