Program only rotates square images properly

145 Views Asked by At

I have been trying to work with PGM files on C++, getting their negatives etc. Now once I started on rotation, I had a rough pseudocode on how we're gonna rotate the matrix, here's the result on a numerical matrix:

Rotated matrix test

On the paper, this seems right. Now when I apply the same algorithm to rotate the images, it only works properly on square image(i.e same height and width):

Rotated Square Image

But on rectangle images, it produces this kind of result:

Rotated Rectangle image

Here's the code:

   void loadRotMatrix()
                    {
                        //transpose of matrix
                        for(int i=0;i<cols;i++)
                        {
                            for(int j=0;j<rows;j++)
                            {
                                rotatedmatrix[i][j] = matrix[j][i];
                            }
                        }
                        //flipped transposed
                        for(int i=0;i<rows;i++)
                        {
                            int temp =0;
                            for(int j=0,k=cols-1;j<k;j++,k--)
                            {
                            temp=rotatedmatrix[j][i];
                            rotatedmatrix[j][i]=rotatedmatrix[k][i];
                            rotatedmatrix[k][i]=temp;
                            }
                        }
                    }

Now I cannot for the life of my decode what's going on here and what is turning my dog into a cerberus :p

2

There are 2 best solutions below

0
On

The shape of the array (width and height) are different when the image is not rectangular.

You will need to rotate the arrayinto a different array for the indices to make sense.

int sourceMatrix[100][200];

int destMatrix[200][100];
3
On

You cannot flip nor transpose non-square matrix. Before doing math, add extra rows or columns to make a matrix square, do the math, then strip the added columns or rows back to get the original image without the padding.