opencv提供了一个简单的旋转图像算子cv::rotate(inimage,outimage,rotate_code),但是该算子仅能选择90°的整数倍,也就是说图像只能正交旋转。
通用仿射变换warpaffine方法可以实现自由旋转,但是需要注意默认的旋转矩阵中,平移分量是原图像的width/2和height/2,也就是说旋转后图像尺寸的变化需要自行考虑处理。
插代码
int width = inimg.cols; int height = inimg.rows;
double r_angle = angle * M_PI / 180;
int new_width = width * cos(r_angle) + height * sin(r_angle);
int new_height = width * sin(r_angle) + height * cos(r_angle);
cv::Mat RotateMat = cv::getRotationMatrix2D(cv::Point2f(width /2, height /2), angle, 1);
RotateMat.at<double>(0, 2) += (new_width / 2 - width / 2);
RotateMat.at<double>(1, 2) += (new_height / 2 - height / 2);
cv::warpAffine(inimg, outimg, RotateMat, cv::Size(new_width, new_height));
旋转效果