项目要用到图像旋转,OpenCV里面居然没有专门封装好的函数,只好自己写了。根据《learnning OpenCV》发现效果不是很理想,旋转后图像大小不变,可是图像却被裁减了。
例子如下:
int main( int argc, char** argv ) { IplImage* src=cvLoadImage("C:\\Users\\Liu\\Desktop\\bridge.bmp",1); IplImage* dst = cvCloneImage( src ); int delta = 1; int angle = 10; double factor; cvNamedWindow( "src", 1 ); cvShowImage( "src", src ); float m[6]; CvMat M = cvMat( 2, 3, CV_32F, m ); int w = src->width; int h = src->height; m[0] = (float)cos(-angle*2*CV_PI/180.); m[1] = (float)sin(-angle*2*CV_PI/180.); m[3] = -m[1]; m[4] = m[0]; // 将旋转中心移至图像中间 m[2] = w*0.5f; m[5] = h*0.5f; // dst(x,y) = A * src(x,y) cvGetQuadrangleSubPix( src, dst, &M); cvNamedWindow( "dst", 1 ); cvShowImage( "dst", dst ); cvWaitKey(0); return 0; }
从上面结果可以看出,效果只能一个字形容,差!
网上程序也有很多,鱼龙混杂的,很多无法运行,下面提供用最基本的OpenCV1.0实现的图像旋转,在高版本的OpenCV中,毫无疑问也可以运行。
int main(int argc, char ** argv) { IplImage* src=cvLoadImage("C:\\Users\\Liu\\Desktop\\bridge.bmp",1); cvNamedWindow( "src", 1 ); cvShowImage( "src", src ); float angle = 15; float anglerad=CV_PI*angle/180.0; //输入图像的大小 int w = src->width; int h = src->height; //旋转后图像的大小 int w_dst = int(fabs(h*sin(anglerad))+fabs(w*cos(anglerad))); int h_dst = int(fabs(w * sin(anglerad)) +fabs(h * cos(anglerad))); CvSize rect; rect.height=h_dst; rect.width=w_dst; //中间变量 IplImage *des=cvCreateImage(rect,src->depth,src->nChannels); //旋转后的图像 IplImage *des_rot=cvCreateImage(rect,src->depth,src->nChannels); //用0填充 cvFillImage(des,0); //设置roi区域,将原图copy到roi区域 CvRect roi; roi.x=(w_dst-w)/2; roi.y=(h_dst-h)/2; roi.height=h; roi.width=w; cvSetImageROI(des,roi); cvCopy(src,des,NULL); cvResetImageROI(des); //旋转矩阵 float m[6]; CvMat M = cvMat( 2, 3, CV_32F, m ); m[0] = (float)cos(-anglerad); m[1] = (float)sin(-anglerad); m[3] = -m[1]; m[4] = m[0]; // 将旋转中心移至图像中间 m[2] = w_dst*0.5f; m[5] = h_dst*0.5f; cvGetQuadrangleSubPix( des, des_rot, &M); cvNamedWindow( "dst", 1 ); cvShowImage("dst",des_rot); cvReleaseImage(&src); cvReleaseImage(&des); cvReleaseImage(&des_rot); cvWaitKey(0); return 0; }
原文地址:http://blog.csdn.net/lsh_2013/article/details/45101937