Showing posts with label Vector Maths. Show all posts
Showing posts with label Vector Maths. Show all posts

Monday, November 12, 2018

Rotating Images

Recently I have been working on a small image processing program built using Processing 3. I wanted to add the ability to rotate the image 90° clockwise or anti-clockwise, but I needed to modify the pixels themselves and figure out where they should be after the rotation.


Original Image

Image Rotated 90° Clockwise


To do this I needed to use Vector Math and more specifically rotating a vector. Each pixel has a position in screen space, made of an x co-ordinate and a y co-ordinate. Depending on the program/engine/framework being used the screen space will start (aka the origin (0, 0)) either in the top left corner or bottom left corner (this will be important later).

To rotate a vector in any angle (ϑ) we use the equation:
New X = v.x * cos(ϑ) - v.y * sin(ϑ)
New Y = v.x * sin(ϑ) + v.y * cos(ϑ)

This will then rotate any vector assuming that you are rotating it around the origin (0, 0), however, you'll most likely want to rotate it using a different pivot point. You could move each pixel relative to the origin, rotate each pixel using the above fomula and then translate that back to the actual pivot point but thats a lot of extra calculations. The equation can be modified to do this all in one go.



New X = (v.x - rotate point.x) * cos(ϑ) - (v.y - rotate point.y) * sin(ϑ) +  rotate point.x
New Y = (v.x - rotate point.x) * sin(ϑ) + (v.y - rotate point.y) * cos(ϑ) +  rotate point.y

Now depending on which way your screen origin is located, you might have to invert the angle, so if your screen origin is in the top left, you are fine and can use 90° to rotate something clockwise. However, if your screen origin is in the bottom left, you unfortunately have to invert the angle, so for 90° clockwise, the angle actually used is -90°.