from PIL import Image import math import numpy as np from numpy import matrix from numpy import linalg def rot_x(angle,ptx,pty): return math.cos(angle)*ptx + -math.sin(angle)*pty def rot_y(angle,ptx,pty): return math.sin(angle)*ptx + math.cos(angle)*pty angle = math.radians(45) im = Image.open('test.jpg') im.rotate(45).save('implemented_rotation.jpg') (x,y) = im.size # T = matrix([[math.cos(angle),-math.sin(angle),-x*math.cos(angle)/2-y*math.sin(angle)/2+x/2],[math.sin(angle),math.cos(angle),-x*math.sin(angle)/2+y*math.cos(angle)/2-y/2],[0,0,1]]) T = matrix([[math.cos(angle),-math.sin(angle),0],[math.sin(angle),math.cos(angle),0],[0,0,1]]) Ttuple = np.array(T).flatten('C') im_rotated_manual = im.transform((x,y),Image.AFFINE,Ttuple,resample=Image.BILINEAR) im_rotated_manual.save('outputpython_rotate_manual.jpg') T = matrix([[2,0,0],[0,0.5,0],[0,0,1]]) Ttuple = np.array(T).flatten('C') im_def = im.transform((1*x,2*y),Image.AFFINE,Ttuple,resample=Image.BILINEAR) im_def.save('outputpython_deform.jpg') T = matrix([[1,math.tan(angle),mnx],[0,1,mny],[0,0,1]]) Ttuple = np.array(T).flatten('C') im_def = im.transform((2*x,2*y),Image.AFFINE,Ttuple,resample=Image.BILINEAR) im_def.save('outputpython_deform2.jpg') xextremes = [rot_x(angle,0,0),rot_x(angle,0,y-1),rot_x(angle,x-1,0),rot_x(angle,x-1,y-1)] yextremes = [rot_y(angle,0,0),rot_y(angle,0,y-1),rot_y(angle,x-1,0),rot_y(angle,x-1,y-1)] mnx = min(xextremes) mxx = max(xextremes) mny = min(yextremes) mxy = max(yextremes) print(mnx) print(mny) T = matrix([[math.cos(angle),-math.sin(angle),-mnx],[math.sin(angle),math.cos(angle),0],[0,0,1]]) # Tinv = linalg.inv(T); # print(Tinv) Ttuple = np.array(T).flatten('C') #Ttuple = (T[0,0],T[0,1], T[0,2], T[1,0],T[1,1],T[1,2]) # print(Tinvtuple) im = im.transform((int(round(mxx-mnx)),int(round((mxy-mny)))),Image.AFFINE,Ttuple,resample=Image.BILINEAR) im.save('outputpython_rotate.jpg')