Search code examples
pythonnumpyscikit-imageaffinetransformpiecewise

Picewise Transformation


I am looking for a function that can uses all the transformation matrix of PiecewiseAffineTransform to apply on the source data to get the destination data at one run. I could use piecewise transformation and I could not find the function for using all the transformation matrix at same time, this code can use all transformation matrix in a loop which is not the right way that should be done ,I also present all the functions of the estimated transformation matrix in the skimage package

import numpy as np
from skimage import transform as tf
from sklearn.metrics import mean_squared_error
from skimage.transform import PiecewiseAffineTransform
src = np.array([0,0 , 1,0 , 1,1 , 0,1]).reshape((4, 2))
dst = np.array([3,1 , 3,2 , 2,2 , 2,1]).reshape((4, 2))
tform = tf.estimate_transform('piecewise-affine', src, dst)
print(src)
print(dst)
print(tform.affines[0].params)
print(tform.affines[1].params)
mt = tf.matrix_transform(src, tform.affines[0].params)
print(mt)



>>> dir(tform)
['__add__', '__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_inverse_tesselation', '_tesselation', 'affines', 'estimate', 'inverse', 'inverse_affines', 'residuals']

Solution

  • Just call tform object with the source data as an argument (see https://github.com/scikit-image/scikit-image/blob/master/skimage/transform/_geometric.py#L871):

    In []: src
    Out[]: 
    array([[0, 0],
           [1, 0],
           [1, 1],
           [0, 1]])
    
    In []: tform(src)
    Out[]: 
    array([[ 3.,  1.],
           [ 3.,  2.],
           [ 2.,  2.],
           [ 2.,  1.]])