# Regions of interest

## Creating a Spherical ROI

In neuroim there is basic support for creating regions of interest (ROI). To create a spherical ROI around a central point, we need an existing object of type `BrainVolume` or `BrainSpace`.

To create a spherical region of interest with a 5mm radius around a central voxel at i=20, j=20, k=20, we can do the following:

``````      # attach MNI BrainSpace instance

data("MNI_SPACE_1MM")

# we create a spherical ROI centered around voxel coordinates [20,20,20] with a 5mm radius,
# filling all values in the ROI with 100.

sphere <- RegionSphere(MNI_SPACE_1MM, c(20,20,20), radius=5, fill=100)

# to extract the voxel coordinates of the sphere:

vox <- coords(sphere)

# to get the values at the coordinate locations

vals <- values(sphere)
all.equal(vals, rep(100, length(vals)))
#>  TRUE
``````

## Creating a Spherical ROI around an MNI coordinate

To create a spherical ROI centered around an real coordinate in mm, we need to first convert the real-valued coordinate to a voxel-based coordinate. Suppose our real-world coordinate is at -50, -28, 10 in MNI space.

``````

rpoint <- c(-50,-28,10)

# Because RegionSphere takes a coordinate in voxel units,
# we need to convert to the real-world MNI coordinate to grid coordinates.

vox <- coordToGrid(MNI_SPACE_1MM, rpoint)
sphere <- RegionSphere(MNI_SPACE_1MM, vox, radius=10, fill=1)
dim(coords(sphere))
#>  4169    3

# convert back to MNI coordinates

mnicoords <- indexToCoord(MNI_SPACE_1MM, indices(sphere))

## compute center of mass of MNI coords in ROI (should be close to original coordinate)
centerOfMass <- colMeans(mnicoords)
centerOfMass
#>  -50.5 -27.5  10.5
``````

## Converting an ROI to a SparseBrainVolume

We may want to convert a region of interest to a BrainVolume instance. But we don't want to store every value in dense grid. Here we can make use of the `SparseBrainVolume` class which only stores non-zero values.

``````
sphere <- RegionSphere(MNI_SPACE_1MM, c(50,50,50), radius=10, fill=1)
sparsevol <- SparseBrainVolume(values(sphere),MNI_SPACE_1MM,indices=indices(sphere))

sum(sparsevol) == sum(values(sphere))
#>  TRUE

all(dim(sparsevol) == dim(MNI_SPACE_1MM))
#>  TRUE
``````