Last active
July 5, 2018 17:06
-
-
Save agisga/8dc19ed8bcb673f3ab9a65536b51e3c9 to your computer and use it in GitHub Desktop.
Make a GIF animation from a set of brain MRI DICOM images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright (c) 2018 Alexej Gossmann | |
# MIT License https://choosealicense.com/licenses/mit/ | |
library(oro.dicom) | |
library(oro.nifti) | |
library(fslr) | |
library(R.matlab) | |
library(tidyverse) | |
library(gganimate) | |
library(doParallel) | |
registerDoParallel(cores = 3) | |
t1_data_dir <- "/path/to/DICOMs/" | |
all_slices <- readDICOM(t1_data_dir) | |
t1_brain_nii <- dicom2nifti(all_slices) | |
n_slices <- length(all_slices[["img"]]) | |
slice_to_df <- function(brain_nii, slice_num) { | |
tmp_mat <- brain_nii@.Data[ , , slice_num] | |
colnames(tmp_mat) <- 1:ncol(tmp_mat) | |
tmp_df <- as_data_frame(tmp_mat) %>% | |
mutate(row_id = 1:nrow(tmp_mat)) %>% | |
gather(col_id, value, -row_id) %>% | |
mutate(col_id = as.integer(col_id)) %>% | |
mutate(slice = slice_num) | |
return(tmp_df) | |
} | |
t1_brain_df <- foreach(i = 1:n_slices, .combine = bind_rows) %dopar% { | |
slice_to_df(t1_brain_nii, i) | |
} | |
p <- ggplot(t1_brain_df) + | |
geom_tile(aes(x = row_id, y = col_id, fill = factor(value), frame = slice)) + | |
scale_fill_grey() + | |
theme_void() + | |
theme(plot.title = element_text(color = "#CCCCCC"), legend.position = "none", | |
plot.background = element_rect(fill = "#333333", color = NA)) + | |
coord_fixed(ratio = pixdim(t1_brain_nii)[2]) + | |
ggtitle("Slice") | |
# width and height set by hand to avoid white borders around the plot | |
w <- 374 | |
h <- 485 | |
gganimate(p, "T1.gif", interval = 0.1, title_frame = TRUE, | |
ani.width = w, ani.height = h) |
Author
agisga
commented
Jul 5, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment