forked from nipraxis/textbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nibabel_affines.Rmd
67 lines (54 loc) · 1.79 KB
/
nibabel_affines.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
---
jupyter:
jupytext:
text_representation:
extension: .Rmd
format_name: rmarkdown
format_version: '1.2'
jupytext_version: 1.11.5
kernelspec:
display_name: Python 3 (ipykernel)
language: python
name: python3
---
# The [`nibabel.affines`](http://nipy.org/nibabel/reference/nibabel.affines.html#module-nibabel.affines) module
```{python}
import numpy as np
np.set_printoptions(precision=4, suppress=True)
import nibabel as nib
```
Neuroimaging images have affines, and we often need to process these
affines, or apply these affines to coordinates.
Nibabel has routines to do this in its `affines` submodule.
The `from_matvec` function is a short-cut to make a 4 x 4 affine matrix from
a 3 x 3 matrix and an (optional) vector of translations.
For example, let’s say I have a 3 x 3 rotation matrix, specifying a rotation
of 0.4 radians around the y axis (see Rotations and rotation matrices):
```{python}
cos_a = np.cos(0.4)
sin_a = np.sin(0.4)
y_rotation = np.array([[ cos_a, 0, sin_a],
[ 0, 1, 0],
[-sin_a, 0, cos_a]])
y_rotation
```
I want to put this 3 x 3 matrix into a 4 x 4 affine matrix:
```{python}
# Affine from a 3x3 matrix (the 'mat' in 'matvec')
nib.affines.from_matvec(y_rotation)
```
You can also add a translation vector in the call to `from_matvec`. The
translation vector is the `vec` of `from_matvec`:
```{python}
# Affine from a 3x3 matrix ('mat') and a translation vector ('vec')
aff = nib.affines.from_matvec(y_rotation, [10, 20, 30])
aff
```
`nibabel.affines.to_matvec` does the reverse operation. It splits the
affine matrix into the top left 3 x 3 matrix, and the translation vector from
the last column of the affine:
```{python}
mat, vec = nib.affines.to_matvec(aff)
mat
vec
```