~/image/e4 で演習
# e401.py ... expand image import Image img = Image.open('s401.ppm') width, height = img.size width = width * 5 height = height * 5 imgx = img.resize((width,height), Image.NEAREST) imgx.save('s401-1.ppm')
u = ax + by + c v = dx + ey + f
(x, y) = ( 10, 50), (380, 100), (130, 280) (u, v) = ( 0, 0), (400, 100), (100, 300)
|u1 v1| |x1 y1 1| |a d| |u2 v2| = |x2 y2 1| |b e| |u3 v3| |x3 y3 1| |c f|
# e403.py ... affine coefficients from scipy import matrix from scipy.linalg import solve U = matrix([[ 0, 0], [400, 100], [100, 300]]) X = matrix([[10, 50, 1], [380, 100, 1], [130, 280, 1]]) C = solve(X, U) print 'a =', C[0][0] print 'b =', C[1][0] print 'c =', C[2][0] print 'd =', C[0][1] print 'e =', C[1][1] print 'f =', C[2][1]
# e404.py ... test affine transform import Image img = Image.open('s404.ppm') imgx = img.transform((400,300), Image.AFFINE, (a, b, c, d, e, f), Image.NEAREST) imgx.save('s404-1.ppm')
# e405.py from math import sqrt from scipy import array import pylab def linreg(X, Y): assert len(X) == len(Y) N = len(X) Sx = Sy = Sxx = Syy = Sxy = 0.0 for x, y in zip(X, Y): Sx = Sx + x Sy = Sy + y Sxx = Sxx + x*x Syy = Syy + y*y Sxy = Sxy + x*y det = Sxx * N - Sx * Sx a = (Sxy * N - Sy * Sx)/det b = (Sxx * Sy - Sx * Sxy)/det return a, b def plot(X, Y, a, b): x = array(X) X0 = x.min() X1 = x.max() Y0 = a * X0 + b Y1 = a * X1 + b pylab.plot(X, Y, 'o', [X0,X1], [Y0,Y1], '-') pylab.show() if __name__=='__main__': #testing X=[1,2,3,4,5] Y=[357.14,153.57,48.78,10.48,-168.8] a, b = linreg(X, Y) plot(X, Y, a, b)