
关键是旋转公式的推导(我是看别人的,呵呵)。有了公式,就很容易实现了。
#include"stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include "cv.h"
#include "highgui.h"
using namespace std;
using namespace cv;
IplImage * oimage, * nimage;
double rx,ry,roangle;
const double pi = 3.14;
int sx,sy;
char *data;
void onTrackerSlid(int pos)
{
rx = oimage->width * 0.5; //旋转点位置
ry = oimage->height * 0.5;
roangle = pos * pi /180; // 角度转换弧度
for(int i = 0; i < oimage->widthStep * oimage->height; i++) // 旋转后图片初始值
data[i] = 0;
for(int x = 0; x < oimage->width; x++)
for(int y =0; y < oimage->height; y++)
{ //新图点(x,y) 到源图(sx,sy)的映射
sx = (int)((x - rx)*cos(roangle) - (y - ry) * sin(roangle) + rx);
sy = (int)((x - rx)*sin(roangle) + (y - ry) * cos(roangle) + ry);
if((sx >= 0 && sx < oimage->width) && (sy >= 0 && sy < oimage->height))
{ //新(x,y)的像素值
data[y * oimage->widthStep + x * oimage->nChannels + 0] = (char )((oimage->imageData + oimage->widthStep * sy)[sx * oimage->nChannels +0]);
data[y * oimage->widthStep + x * oimage->nChannels + 1] = (char )((oimage->imageData + oimage->widthStep * sy)[sx * oimage->nChannels +1]);
data[y * oimage->widthStep + x * oimage->nChannels + 2] = (char )((oimage->imageData + oimage->widthStep * sy)[sx * oimage->nChannels +2]);
}
}
cvShowImage("new",nimage);
}
int main()
{
oimage = cvLoadImage("C:\\Users\\LC\\Desktop\\常用标准图\\Lena.jpg"); //读入测试图片
printf("%d %d %d",oimage->widthStep,oimage->nChannels,oimage->depth);
nimage = cvCreateImageHeader(cvGetSize(oimage),oimage->depth,oimage->nChannels); //开辟数据
data = (char *)(malloc(sizeof(char)*oimage->widthStep * oimage->height));
if(!oimage || !nimage || !data)
{
printf("memery error");
return -1;
}
int threshold=30; //初始值
nimage->imageData = data;
cvNamedWindow("old",1);
cvNamedWindow("new",1);
cvShowImage("old",oimage);
cvCreateTrackbar("angle","new",&threshold,360,onTrackerSlid); //创建滑块
onTrackerSlid(threshold);
cvWaitKey();
cvDestroyWindow("old");
cvDestroyWindow("new");
cvReleaseImage(&oimage);
cvReleaseImage(&nimage);
return -1;
}