rasterio / affine

Affine transformation matrices
BSD 3-Clause "New" or "Revised" License
156 stars 28 forks source link

[Enhancement] Affine to be transparently multipliable with Numpy arrays #68

Closed Multihuntr closed 2 years ago

Multihuntr commented 2 years ago

I think that most people who are using affine will also be using rasterio and, thus, working with numpy arrays. It would be nice to be able to transparently batch convert numpy arrays of coordinates with just anAffine * aNumpyArray.

As far as I know, it's standard to have lists of coordinates in numpy arrays shaped [..., 2] because it makes operations like "add (2, 1) to all coordinates" a very simple numpy operation (arr + (2, 1)).

This is what I would like to work:

import affine
import numpy as np
arr = np.array([(1, 1), (4, 6), (2, 5), (3, 1)])
aff = affine.Affine(2, 0, 3, 0, 3, 1) # scale up by (2, 3), offset by (3, 1)
print(arr * aff)

There is a work-around: you can transpose the input, and combine back into a numpy array with:

>>> print(np.array(aff * arr.T).T)
[[ 5.  4.]
 [11. 19.]
 [ 7. 16.]
 [ 9.  4.]]

But, I think it would be much nicer if aff * arr was just supported to do this operation automatically.

sgillies commented 2 years ago

@Multihuntr thank you for showing the work around. I think we should not add this feature. As you point out, we only have to write one line of code in our applications to batch multiply.

Multihuntr commented 2 years ago

Sure thing. Makes sense.