- /* 程序名:rotate.c
- 功能:读入图像文件,做图像旋转转,然后显示图像在屏幕上
- */
- #include <stdlib.h>
- #include <stdio.h>
- #include <math.h>
- #include <cv.h>
- #include <highgui.h>
- void myRotate(IplImage *img, int x, int y, float degree,int center[2]);
- int main(int argc, char *argv[])
- {
- IplImage* img = 0;
- int height,width,step,channels;
- uchar *data;
- int center[2]={0,0};
- argv[1]="d://a_base_1.jpg";
- //请自己添加图像文件路径
- img=cvLoadImage(argv[1],1);
- if(!img)
- {
- printf("Could not load image file: %s/n",argv[1]);
- exit(0);
- }
- // 获取图像信息
- height = img->height;
- width = img->width;
- step = img->widthStep;
- channels = img->nChannels;
- data = (uchar *)img->imageData;
- printf("Processing a %dx%d image with %d channels/n",height,width,channels);
- // 创建窗口
- cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE);
- cvMoveWindow("mainWin", 100, 100);
- center[0]=width/2;//这两句可以设置旋转中心的坐标
- center[1]=height/2;
- // 反转图像
- myRotate(img,0,0,-1,center);
- // 显示图像
- cvShowImage("mainWin", img );
- cvWaitKey(0);
- cvReleaseImage(&img );
- return 0;
- }
- void myRotate(IplImage *img, int x, int y, float degree,int center[2])
- {
- double angle = degree * CV_PI / 180.; // 角度(弧度)
- double a = sin(angle), b = cos(angle); // 正弦和余弦的角度
- IplImage* imgSrc=cvCloneImage(img);
- int w_src = imgSrc->width;
- int h_src = imgSrc->height;
- // 使w_dst和h_dst适合输出图像
- //int w_dst = int(h_src * a + w_src * b);
- //int h_dst = int(w_src * a + h_src * b);
- //int w_dst = int(h_src * abs(a) + w_src * abs(b));
- // int h_dst = int(w_src * abs(a) + h_src * abs(b));
- // 用于WarpAffine的映射矩阵,存储在堆栈数组中
- double map[6];
- CvMat map_matrix = cvMat(2, 3, CV_64FC1, map);
- // cv2DRotationMatrix需要旋转中心
- CvPoint2D32f pt = cvPoint2D32f(center[0], center[1]);
- cv2DRotationMatrix(pt, degree, 1.0, &map_matrix);
- // 否则你将只得到结果的一部分
- map[2] +=x;
- map[5] +=y;
- // 我们需要一个目的地图像
- cvWarpAffine(
- imgSrc,
- img,
- &map_matrix,
- CV_INTER_LINEAR | CV_WARP_FILL_OUTLIERS,
- cvScalarAll(0)
- );
- }