from macslib import *
from numpy import *
from numpy.linalg import pinv
from math import *

img = loadImage('cat.jpg')
numRows = len(img)
numCols = len(img[0])

az = radians(30)
ax = radians(-0.3)
ay = radians(-0.3)
center = [numCols/2,numRows/2]

transform = array([
    [-0.6,0,0,0],
    [0,-0.6,0,30],
    [0,0,1,0],
    [0,0,0,1]])
transform = transform.dot(array([
    [1, 0      , 0       , 0],
    [0, cos(ax), -sin(ax), 0],
    [0, sin(ax), cos(ax) , 0],
    [0, 0      , 0       , 1]]))
transform = transform.dot(array([
    [cos(ay) , 0, sin(ay), 0],
    [0       , 1, 0      , 0],
    [-sin(ay), 0, cos(ay), 0],
    [0       , 0, 0      , 1]]))
transform = transform.dot(array([
    [cos(az) , sin(az), 0, 0],
    [-sin(az), cos(az), 0, 0],
    [0       , 0      , 1, 0],
    [0       , 0      , 0, 1]]))
    
project = array([
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 0, 1],
    [0, 0, 1, 0]])
    
centerMatrix = array([
    [1, 0, 0, -center[0]],
    [0, 1, 0, -center[1]],
    [0, 0, 1, 0         ],
    [0, 0, 0, 1         ]])
antiCenterMatrix = array([
    [1, 0, 0, center[0]],
    [0, 1, 0, center[1]],
    [0, 0, 1, 0        ],
    [0, 0, 0, 1        ]])
    
transform = antiCenterMatrix.dot(project).dot(transform).dot(centerMatrix)

print transform.dot(array([[0],[0],[1],[1]]))[:,0]
print transform.dot(array([[0],[numCols-1],[1],[1]]))[:,0]
print transform.dot(array([[numRows-1],[numCols-1],[1],[1]]))[:,0]

srcImg = img
img = zeros((numRows,numCols))
for row in range(numRows):
    for col in range(numCols):
        pixel = array([[col],[row],[1],[1]])
        srcPixel = transform.dot(pixel)
        srcCol,srcRow = int(srcPixel[0][0]/srcPixel[3][0]), int(srcPixel[1][0]/srcPixel[3][0])
        if srcRow>=0 and srcRow<numRows and srcCol>=0 and srcCol<numCols:
            img[srcRow][srcCol] = srcImg[row][col]

drawImage(img)
