I am writing some code that rotates an OpenCV Mat by a specified angle. Using the following code, I have successfully rotated the Mat around its center, but due to the fact that the image is not square, the center of the rotated image is not the center of the new image, and part of the image falls outside of the new Mat.
Point2f src_center(source.cols/2.0F, source.rows/2.0F);
Mat rot_mat = getRotationMatrix2D(src_center, angle, 1.0);
Mat final;
final.create(calculateHeight(source.cols, source.rows, angle), calculateWidth(source.cols, source.rows, angle), CV_32FC1);
warpAffine(source, final, rot_mat, final.size());
Note: calculateHeight and calculateWidth are methods that simply determine the size of the new Mat based on the dimensions of the original Mat and the angle that it is being rotated.
Example: Original image rotates to: rotated image
How do I rotate the Mat in such a way that the resulting rotated Mat is centered within the boundaries?