--- title: "Working with Image Volumes" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Working with Image Volumes} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, echo = FALSE, message = FALSE} knitr::opts_chunk$set(collapse = T, comment = "#>") ``` ## Reading a NIFTI formatted image volume The way to read an volumetric image file is to use `read_vol`: ```{r} library(neuroim2) file_name <- system.file("extdata", "global_mask2.nii.gz", package="neuroim2") vol <- read_vol(file_name) ``` ## Working with image volumes Information about the geometry of the image volume is shown here: ```{r} print(vol) ``` `read_vol` returns an object of class `NeuroVol` object 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 `array`s: ```{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) class(vol2) print(vol2[1,1,1]) ``` We can also create a `NeuroVol` instance from an `array` or `numeric` vector. First we consruct a standard R `array`: ```{r} x <- array(0, c(64,64,64)) ``` Now we reate a `NeuroSpace` instance that describes the geometry of the image including, at minimum, its dimensions and voxel spacing. ```{r} bspace <- NeuroSpace(dim=c(64,64,64), spacing=c(1,1,1)) vol <- NeuroVol(x, bspace) vol ``` We do not usually have to create `NeuroSpace` objects, because geometric information about an image is automatically determined from information stored in the image file header. Thus, `NeuroSpace` objects are usually copied from existing images using the `space` extractor function when needed: ```{r} vol2 <- NeuroVol((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 `write_vol` ```{r eval=FALSE} write_vol(vol2, "output.nii") ## adding a '.gz' extension results ina gzipped file. write_vol(vol2, "output.nii.gz") ```