norm <- dnorm(seq(-5, 5, length=32), sd=2)
norm <- (norm-min(norm)) / max(norm-min(norm))
img <- outer(outer(norm, norm), norm)
img <- round(255 * img)
img[17:32,,] <- 255 - img[17:32,,]
img.nifti <- nifti(img) # create NIfTI object
fname = file.path(tempdir(), "test-nifti-image-uint8")
writeNIfTI(img.nifti, fname, verbose=TRUE)
## These files should be viewable in, for example, FSLview
## Make sure you adjust the min/max values for proper visualization
data <- readNIfTI(fname, verbose=TRUE)
image(img.nifti, oma=rep(2,4), bg="white")
image(data, oma=rep(2,4), bg="white")
abs.err <- abs(data - img.nifti)
image(as(abs.err, "nifti"), zlim=range(img.nifti), oma=rep(2,4),
bg="white")
if (FALSE) {
## Loop through all possible data types
datatypes <- list(code=c(2, 4, 8, 16, 64),
name=c("uint8", "int16", "int32", "float", "double"))
equal <- vector("list")
for (i in 1:length(datatypes$code)) {
fname <- paste("test-nifti-image-", datatypes$name[i], sep="")
fname = file.path(tempdir(), fname)
rm(img.nifti)
img.nifti <- nifti(img, datatype=datatypes$code[i])
writeNIfTI(img.nifti, fname, verbose=TRUE)
equal[[i]] <- all(readNIfTI(fname) == img)
}
names(equal) <- datatypes$name
unlist(equal)
}
Run the code above in your browser using DataLab