Mat AngelRotate(Mat src, int angle)
{
float alpha = angle * CV_PI / 180;
float rotateMat[3][3] = {
{cos(alpha), -sin(alpha), 0,},
{sin(alpha), cos(alpha), 0,},
{0,0,1} };
int nSrcRows = src.rows;
int nSrcCols = src.cols;
float a1 = nSrcCols * rotateMat[0][0];
float b1 = nSrcCols * rotateMat[1][0];
float a2 = nSrcCols * rotateMat[0][0] + nSrcRows *rotateMat[0][1];
float b2 = nSrcCols * rotateMat[1][0] + nSrcRows *rotateMat[1][1];
float a3 = nSrcRows * rotateMat[0][1];
float b3 = nSrcRows * rotateMat[1][1];
float kxMin = min(min(min(0.0f, a1), a2), a3);
float kxMax = max(max(max(0.0f, a1), a2), a3);
float kyMin = min(min(min(0.0f, b1), b2), b3);
float kyMax = max(max(max(0.0f, b1), b2), b3);
int nRows = abs(kxMax - kxMin);
int nCols = abs(kyMax - kyMin);
Mat dst(nRows, nCols, src.type(), Scalar::all(0));
for (int i = 0; i < nRows; i++)
{
for (int j = 0; j < nCols; j++)
{
int x = (j + kxMin)* rotateMat[0][0] - (i + kyMin) * rotateMat[0][1];
int y = -(j + kxMin) * rotateMat[1][0] + (i + kyMin) * rotateMat[1][1];
if (x >= 0 && x < nSrcCols && y >= 0 && y < nSrcRows) dst.at<Vec3b>(i, j) = src.at<Vec3b>(y, x);
}
}
return dst;
}
效果图:
Mat GetRotationMatrix2D(Point2f center, double angle, double scale)
{
angle *= CV_PI / 180;
double alpha = cos(angle) * scale;
double beta = sin(angle) * scale;
Mat M(2, 3, CV_64F);
double *m = (double *)M.data;
m[0] = alpha;
m[1] = beta;
m[2] = (1 - alpha) * center.x - beta * center.y;
m[3] = -beta;
m[4] = alpha;
}
Mat picture = imread("E:\\VS\\2020\\opencvtt\\x64\\Debug\\1111.jpg");
if (!picture.data) return -1;
imshow("srcImage", picture);
//int angle = 30;
//Mat resImage = AngelRotate(picture, angle);
Mat resImage = Mat::zeros(picture.rows, picture.cols, picture.type());
Point2f centerPoint = Point2f(picture.rows / 2, picture.cols / 2);
double angle = 30;
double scale = 1.0;
Mat warpMat = GetRotationMatrix2D(centerPoint, angle, scale);
warpAffine(picture, resImage, warpMat, resImage.size());//仿射变换
imshow("desImage", resImage);
waitKey(0);
效果图: