Numpy vnl bridge unexpected behavior

(Simon Rit) #1

I tend to write too many things on the same line in Python and this caused an unexpected behavior for the numpy vnl bridge. It occurred in a different context but I have the following minimal example

import itk
m = itk.Matrix[itk.D,4,4]()
m2 = m+m

which should show the same two matrices but actually shows

[[4.68850067e-310 0.00000000e+000 0.00000000e+000 0.00000000e+000]
 [0.00000000e+000 2.00000000e+000 0.00000000e+000 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000 2.00000000e+000 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000 0.00000000e+000 2.00000000e+000]]
[[2. 0. 0. 0.]
 [0. 2. 0. 0.]
 [0. 0. 2. 0.]
 [0. 0. 0. 2.]]

Any clue what’s going on and if this can and should be corrected? It seems to be some memory release before the deep copy of the numpy array but I could not see what was wrong in the bridge code.
Thanks in advance!

(Matt McCormick) #2

@fbudin any ideas?

(Francois Budin) #3

No idea, but it is worth the look. Interestingly enough, since the implementation between images and VNL matrices are similar for the NumPy bridge, this problem could potentially arise with images…

(Francois Budin) #4

As a follow up, trying:

In [7]: a=(m+m).GetVnlMatrix()

In [8]: print(itk.GetArrayFromVnlMatrix(a.as_matrix()))
[[4.65803687e-310 6.90632463e-310 6.90632461e-310 6.90632465e-310]
 [6.90632463e-310 6.90632463e-310 6.90632464e-310 6.90632464e-310]
 [6.90632463e-310 6.90632464e-310 6.90632463e-310 6.90632463e-310]
 [6.90632462e-310 6.90632462e-310 6.90632461e-310 6.90632464e-310]]

also returns garbage, which makes me think that the problem is in GetVnlMatrix(), not in the bridge part.

This is most likely due to the return by reference here.