圖像旋轉

關鍵是旋轉公式的推導(我是看別人的,呵呵)。有了公式,就很容易實現了。
#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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章