Say I have a grayscale image 2 pixels width 3 pixels height. And I want to rotate it on some angle. For example, I will rotate it on 90 degrees. I will use the matrices for the forward and backward transformations like this:
| col1 | col2 |
|---|---|
| 0 | -1 |
| 1 | 0 |
| col1 | col2 |
|---|---|
| 0 | 1 |
| -1 | 0 |
First I calculate the rotated bounding rect, by transforming the points of the input rect and calculating boundingRect on them and for the current example it simply becomes like this:
cv::Rect inputRect(0, 0, 2, 3);
// calculations
cv::Rect rotatedRect(-3, 0, 3, 2);
Next I want to use a function from opencv: cv::remap to calculate the values of all the pixels in an image. But to do so, first I need to calculate the mapping matrices. I do it simply like this:
cv::Size rotated(3, 2);
cv::Matx<float, 2, 2> backward {0, 1, -1, 0};
auto mapX = cv::Mat_<float>::zeroes(rotated);
auto mapY = cv::Mat_<float>::zeroes(rotated);
for (int row = 0; row < rotated.height; row++)
for (int col = 0; col < rotated.width; col++)
{
cv::Vec<float, 2> input(rotatedRect.x + col, rotatedRect.y + row)
cv::Vec<float, 2> output = backward * input;
mapX(row, col) = output[0];
mapY(row, col) = output[1];
}
The problem is that this code generates the following x and y map matrices:
| col1 | col2 | col3 |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 1 | 1 |
| col 1 | col 2 | col3 |
|---|---|---|
| 3 | 2 | 1 |
| 3 | 2 | 1 |
which lead to an image with the black line of pixels on the left side because y coordinates of 3 are out of the input matrix range.
I absolutely understand that I met the problem with the difference of matrix size/pixel index, but I can’t understand how to fix it…