Optimized matrix code for rotated images, code by @bendmorris