参考:
https://blog.csdn.net/cl2227619761/article/details/79897804
https://blog.csdn.net/weixin_30641465/article/details/98899952
以下代码可以实现在保持图片尺寸的情况下,旋转图片(不过好像还有角落那里有点黑边,有能力的同学去看看前面提到的博客看源码,看能不能解决)
//crop 是否裁剪
void cropRotateImage(const cv::Mat &source, cv::Mat &dst, double angle, bool crop )
{
angle = fmod(angle, 360.0);//double类型取余数
cv::Point2f center = cv::Point2f(source.rows / 2, source.rows / 2);
double scale = 1; // 缩放尺度
cv::Mat rotateMat;
rotateMat = cv::getRotationMatrix2D(center, angle, scale);
Mat temp;
cv::warpAffine(source, temp, rotateMat, source.size());
if(crop == false)
{
dst = temp.clone();
}
else
{
int h = source.rows;
int w = source.cols;
double angle_crop = fmod(angle, 180.0);
if(angle > 90)
{
angle_crop = 180 - angle_crop;
}
double theta = angle_crop * CV_PI / 180.0;
double hw_ratio = float(h) / float(w);
double tan_theta = tan(theta);
double numerator = cos(theta) + sin(theta) * tan(theta);
double r = h > w ? hw_ratio : (1.0 / hw_ratio);
double denominator = r * tan_theta + 1.0;
double crop_mult = numerator / denominator;
int w_crop = int(crop_mult * w);
int h_crop = int(crop_mult * h);
int x0 = int((w - w_crop) / 2);
int y0 = int((h - h_crop) / 2);
cv::Rect2i roi(x0, y0, w_crop, h_crop);
cv::resize(temp(roi), dst, source.size());
}
}
调用就这样子调用
Mat img = imread("1.bmp");
Mat rotatedMat;
Mat cropRotatedMat;
cropRotateImage(img, rotatedMat, 45, false);
cropRotateImage(img, cropRotatedMat, 45, true);
imshow("img", img);
imshow("rImg", rotatedMat);
imshow("crImg", cropRotatedMat);