---
title: "Working with Image Volumes"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Working with Image Volumes}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
---

```{r, echo = FALSE, message = FALSE}
knitr::opts_chunk$set(collapse = T, comment = "#>")
library(neuroim)
```

## Reading a NIFTI formatted image volume

The easiest way to read an image file is to use `loadVolume`:


```{r}
    fileName <- system.file("extdata", "global_mask.nii", package="neuroim")
    vol <- loadVolume(fileName)
```

## Working with image volumes

Information about the geometry of the image volume is easily accessed:


```{r}
    print(vol)
```

`loadVolume` returns an object of class `DenseBrainVolume` which extends an R `array' and has 3 dimensions (x,y,z).

```{r}
    class(vol)
    
    is.array(vol)
    
    dim(vol)
    
    vol[1,1,1]
    
    vol[64,64,24]
    
```
    
Arithmetic can be performed on images as if they were ordinary arrays:


```{r}
    
    vol2 <- vol + vol
    sum(vol2) == 2 * sum(vol)
    
    vol3 <- vol2 - 2*vol
    all(vol3 == 0)
```

A numeric image volume can be converted to a binary image as follows:


```{r}
    
    vol2 <- as.logical(vol)
    print(vol2[1,1,1])
```

We can also create a `BrainVolume` instance from an `array` or `numeric` vector:


```{r}
    # create an 64X64X64 array of zeros 
    x <- array(0, c(64,64,64))
    
    # create a 'BrainSpace' instance that describes the geometry of the image including, at minimu its dimensions and voxel spacing
    bspace <- BrainSpace(Dim=c(64,64,64), spacing=c(1,1,1))
    vol <- BrainVolume(x, bspace)
    vol
```

We do not usually have to create `BrainSpace` objects because this information is usually read from disk. Thus, `BrainSpace` objects are usually copied from existing images using the `space` extractor function when needed:


```{r}
    vol2 <- BrainVolume((vol+1)*25, space(vol))
    max(vol2)
    
    space(vol2)
```

## Writing a NIFTI formatted image volume

When we're ready to write an image volume to disk, we use `writeVolume`

```{r}
    writeVolume(vol2, "output.nii")
    
    ## adding a '.gz' extension results ina gzipped file.
    writeVolume(vol2, "output.nii.gz")
```





