更新时间:2016-03-24 17:04:29浏览次数:1+次
废话不多说,直接上代码:
/*****************************************
*inputim:要旋转的图像
*tempImg:结果图像
*angle:旋转角度,(逆时针为正,顺时针为负)
*/
void warpFfine (Mat &inputIm,Mat &tempImg,float angle)
{
CV_Assert(!inputIm.empty());
Mat inputImg;
inputIm.copyTo(inputImg);
float radian = (float) (angle /180.0 * CV_PI);
//填充图像使其符合旋转要求
int uniSize =(int) ( max(inputImg.cols, inputImg.rows)* 1.414 );
int dx = (int) (uniSize - inputImg.cols)/2;
int dy = (int) (uniSize - inputImg.rows)/2;
copyMakeBorder(inputImg, tempImg, dy, dy, dx, dx, BORDER_CONSTANT);
//旋轉中心
Point2f center( (float)(tempImg.cols/2) , (float) (tempImg.rows/2));
Mat affine_matrix = getRotationMatrix2D( center, angle, 1.0 );
//旋轉
warpAffine(tempImg, tempImg, affine_matrix, tempImg.size());
//旋轉后的圖像大小
float sinVal = fabs(sin(radian));
float cosVal = fabs(cos(radian));
Size targetSize( (int)(inputImg.cols * cosVal + inputImg.rows * sinVal),
(int)(inputImg.cols * sinVal + inputImg.rows * cosVal) );
//剪掉四周边框
int x = (tempImg.cols - targetSize.width) / 2;
int y = (tempImg.rows - targetSize.height) / 2;
Rect rect(x, y, targetSize.width, targetSize.height);
tempImg = Mat(tempImg, rect);
}
效果:
相关资讯