0

I have a matrix A[M][M] and I want to rotate it N degrees relative to the center of the matrix, discarding the values which its new position is outside the original matrix and filling the missing values with zeroes. I am using the following formula to get he new positions:

newXPosition = ceil(cos(N*PI/180)*(oldXPosition - M/2) - sin(N*PI/180)*(oldYPosition - M/2) + M/2)
newYPosition = ceil(sin(N*PI/180)*(oldXPosition - M/2) + cos(N*PI/180)*(oldYPosition - M/2) + M/2)

However, this is failing at some point. If we look for newXPosition and newYPosition for oldXPosition = oldYPosition = 0, M = 32 and N = 90º, We get newXPosition = 32, newYPosition = 0. Taking into account that the dimensions are [0-31], it will not work to just substract one to newXPosition because in other occasions it would be newYPosition the variable that will have to be substracted, or even both.

Does anyone know where am I failing?

PS: I have already read a couple of answers regarding the 90 degrees rotation, but my intention is not to rotate the matrix 90 degrees, but N.

Community
  • 1
  • 1
Alvaro Gomez
  • 350
  • 2
  • 7
  • 22
  • cos / sin don't take degrees as arguments, they take [radians](http://www.cplusplus.com/reference/cmath/cos/) – UKMonkey Nov 01 '16 at 11:55
  • If the extend of the image is from 0 to 31 then the true center is 31/2=15.5 -- Alternatively, since you are discarding pixels outside the boundaries, your example is just one such pixel. – Lutz Lehmann Nov 01 '16 at 11:56

1 Answers1

1

If you think as each pixel as a small square you see that their center is at 0.5, 1.5 etc; so add "0.5" to oldXPosition - and subtract it when forming newXPosition:

newXPosition = ceil(cos(NPI/180)(oldXPosition+0.5- M/2) - sin(NPI/180)(oldYPosition+0.5- M/2)+M/2-0.5)

So, in your case newXPosition would be 31 - not 32, and newYPosition 0.

I would also recommend you to reverse the logic, so instead of figuring out the new positions based on old x and y, you start with the new matrix and for each pixel you find out the old position that corresponded to (which is like rotating -N degrees with your formulas) - and take the value from that one.

Otherwise a "solid" shape might get zeros due to the rotation.

Instead of "ceil" you might do some fancy interpolation.

Hans Olsson
  • 11,123
  • 15
  • 38