I'm trying to rotate a 1296x968 image by 90 degrees using the C++ API of OpenCV and I'm facing a few problems.
Input:
Rotated:
As you can see, the rotated image has a few problems. First, it has the same size of the original, even though I specifically create the destination Mat
with the inverted size of the original. As a result, the destination image gets cropped.
I suspect this is happening because I'm calling warpAffine()
and passing the size of the original Mat
instead of the size of destination Mat
. But I'm doing this because I followed this answer, but now I suspect that the answer may be wrong. So this is my first doubt/problem.
The second, is that warpAffine()
is writing to the destination at a certain offset (probably to copy the rotated data to the middle of the image) and this operation leaves a horrible and large black border around the image.
How do I fix these issues?
I'm sharing the source code below:
#include <cv.h>
#include <highgui.h>
#include <iostream>
using namespace cv;
using namespace std;
void rotate(Mat& image, double angle)
{
Point2f src_center(image.cols/2.0F, image.rows/2.0F);
Mat rot_matrix = getRotationMatrix2D(src_center, angle, 1.0);
Mat rotated_img(Size(image.size().height, image.size().width), image.type());
warpAffine(image, rotated_img, rot_matrix, image.size());
imwrite("rotated.jpg", rotated_img);
}
int main(int argc, char* argv[])
{
Mat orig_image = imread(argv[1], 1);
if (orig_image.empty())
{
cout << "!!! Couldn't load " << argv[1] << endl;
return -1;
}
rotate(orig_image, 90);
return 0;
}
See Question&Answers more detail:os