Stand With Ukraine

Wednesday, August 10, 2011

How I implemented 2d affine transform in python

Although there is nothing special about it, but, strangely, I could not find it in GDAL-python (though it is very good library for working with raster and shape files, and I like it), also I looked at another respected library - shapely, but unfortunately, there is no capability to move, rotate or translate the shapes (but still there are some very handy functions like union, intersection, distance, area, ..). Another thing is that this can be easily done in Java using JTS, like this:
first I construct a polygon at the origin of the coordinate system and then determine the transformation needed to obtain this unit rectangle from the initial polygon (It can be defined uniquely using height of the polygon and the coordinates of the centers of the parallel edges). Then using the inverse transform we obtain the geometry object corresponding to the specification above (height, coordinates of the centers of the parallel sides). I drew these polygons using their wkt representation in OpenJump.


And still I decided to use python, since there exists an easy way of displaying results in matplotlib. Some people use descartes library for this purpose, but I don't feel like installing another dependency, since the thing with python is that if you change the OS, you have to reinstall them all. For me it is: matplotlib, numpy, scipy, gdal, cdat, shapely, netcdf4-python.... Well, I am getting distracted from the main point. So briefly, I feed my geometries to matplotlib as follows:

So the transformation I did, can be initialized using 3 source and 3 corresponding destination points, that shoud not lie on the same line. Tested it, kind of works. Probably will optimize and improve it later, if necessary, but for now it looks like this:
Basically, I just solve a system of linear equations with respect to parameters of the transformation, and then use the parameters to transform other points.


No comments: