myGUIDE

|

random notes, random thoughts

Archive for November, 2011

Splitting 4D Nifti file into a series of 3D files in Matlab

Saturday, November 12th, 2011

NIfTI-1 is a data format proposed by the NifTI (Neuroimaging Informatics Technology Initiative) DFWG (Data Format Working Group) that can be used for storing neuroimaging datasets (e.g. MRI, functional MRI, etc.). This format is adapted from the widely used ANALYZE 7.5 format from Mayo Clinic. A Nifti file consists of a header part containing the meta-data and the raw image data itself. The header and the image data can be stored together in the same file with an *.nii extension or can be split into two files with an *.hdr extension for the header and an *.img extension for the image data.

For functional MRI, it is not uncommon to store the dataset in a single 4D (3D space + time) Nifti file, especially when experiments involved several hundreds of image volumes. Just imagine the convenience of working with a single file as compared to several hundreds of files. However, there are also instances when it is convenient to manipulate datasets one volume at a time. In this case, having a single volume stored in a single file is very handy.

In this post, I will outline a simple Matlab script that can be used to extract the 3D images from the 4D NifTI file. The script uses some SPM functions such as spm_select()spm_vol(), spm_read_vols(), and spm_write_vol(). Type “help function_name” in Matlab for a description of each function. Be sure that SPM is in Matla’s path before using this script. Without further ado, here is the full function list:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function abk_4Dto3D(fname)
% function abk_4Dto3D(fname)
%
% Splits a 4D nifti file into a series of 3D nifti files.
% Needs SPM functions to work. If input file is fdata.nii,
% the output files will have filenames like fdata_001.nii,
% fdata_002.nii, etc.
 
if (nargin < 1)
    [fname,sts] = spm_select;
    if (sts == 0)
        fprintf('abk_4Dto3D: Operation cancelled.\n');
        return;
    end
end
 
vol = spm_vol(fname);
img = spm_read_vols(vol);
sz = size(img);
 
tvol = vol(1);
tvol = rmfield(tvol,'private');
tvol.descrip = 'generated by abk_4Dto3D.m';
 
[dn,fn,ext] = fileparts(fname);
 
for ctr=1:sz(4)
    tvol.fname = sprintf('%s%s%s_%.3d%s',dn,filesep,fn,ctr,ext);
    fprintf('Writing %s\n',tvol.fname);
    spm_write_vol(tvol,img(:,:,:,ctr));
end
fprintf('done.\n');
end

The script accepts a filename, given by the fname input parameter, of the 4D Nifti file. If fname is not specified, the script will prompt the user to select a file using spm_select(). Once the filename is specified, it will then read the 4D image data, and save it back one 3D image at a time.

Now to the code. Line 1 is simply the usual Matlab function declaration. This is followed by several lines of comments starting with the % character (lines 2 – 7). In line 9, the script checks if the function was called with an input parameter. If none was provided, it prompts the user to make a selection (line 10). It then checks if the user cancelled the operation (lines 11 – 14) and returns if true. Otherwise, it reads the header information using SPM’s spm_vol() function (line 17), loads the 4D data into img variable (line 18) using spm_read_vols(), and gets the image dimension (line 19).

In lines 21 – 23, the header information is copied into the tvol variable (line 21), which will be used later to save the images. The private field of tvol is then removed (line 22) and the header description is changed (line 23) to indicate the new file generator. In line 25, the filename is split into three variables dn, fn, and ext correspoding to the directory location, the base filename, and the extension, respectively.

In lines 27 – 31 is where the 4D image data is actually split into a series of 3D image files. Note how the variable tvol is repeatedly used, changing only the fname field each time. This is because the 3D images have basically the same header information.

Note that the same function could also be used to extract only certain volumes from the 4D nifti files with a slight modification. To implement this, we need to change the function declaration in line 1 into:

function abk_4Dto3D(fname,idx)

where the additional parameter idx is a vector containing the volume numbers to extract. We also need to change lines 27 – 31 as follows:

1
2
3
4
5
for ctr=1:length(idx)
    tvol.fname = sprintf('%s%s%s_%.3d%s',dn,filesep,fn,ctr,ext);
    fprintf('Writing %s\n',tvol.fname);
    spm_write_vol(tvol,img(:,:,:,idx(ctr)));
end

ctr now runs from 1 to the total number of volumes to extract given by the length of idx. The filenames will still be consecutively numbered from 1 to the length of idx (line 2). But this time, the 3D images that are saved are only the volumes specified in idx (line 4).

Have questions, leave a comment.

Looking at how the brain works in real-time

Sunday, November 6th, 2011

Re-posting this article on real-time functional MRI I wrote several years ago.

The technique known as functional magnetic resonance imaging (fMRI) has been extensively used to elucidate the functions of the human brain. Functional MRI provides a “window” where we can see what part of the brain is involved when we think, smell, taste, feel, or move. These windows are the activation maps indicating sites in the subject’s brain that are activated while the subject performs a given task and are usually obtained after analyzing voluminous amount of functional MRI images.

In a typical fMRI scanning session, the accumulated data can reach several hundreds of brain image volumes. The computational demand is usually very high that functional analyses are often delayed and activation maps are obtained long after the scanning session is completed and the subject is no longer inside the MR scanner. In most cases, this delay in analysis is often not an issue. However, the problem arises when after the analysis the data turned out to be corrupted with significant noise that no reliable activation could be extracted resulting in a waste of scanning time and delaying progress in research. To avoid this, the ideal scenario would be to “know” the results while the subject is still inside the MR scanner and before the experiment is concluded. This scenario calls for the immediate analysis of fMRI images as they are acquired and thus motivated the development of the real-time analysis of fMRI data.

Fig. 1. The conceptual framework of the real-time functional magnetic resonance imaging system composing of an MR scanner, a data storage device, and a computational server.

The real-time analysis of fMRI data offers several advantages both for theoretical studies and clinical applications. With real-time analysis, monitoring the task performance of the subject and the resulting quality of the acquired data can be easily achieved. It could also make functional mapping experiment more interactive by allowing ongoing paradigms to be altered if a need arises, making fMRI a more flexible tool for neurological investigations. Moreover, it also enables researchers to locate regions of interest that could be used for the next experimental run.

Fully real-time fMRI analysis could also provide an immediate feedback of the subject’s “ongoing” brain activity and thus enabling researchers to investigate the dynamical nature of the human brain. From a clinical perspective, some applications of real-time fMRI could be in pre-surgical planning. For instance, a surgeon operating a lesion could use functional brain studies to minimize the extent of the damage that could result in the operation. Real-time results of these functional studies are therefore critical. In spreading disorders such as Jacksonian seizures or migraine, the possibility of observing activation maps of such phenomena in real time could lead to a better understanding of the spreading mechanism of the disorder as well as to the development of therapeutic interventions to arrest the symptoms progression.

By providing an immediate feedback of the patient’s brain activity, real-time fMRI could also be used in assessing recovery treatment after a loss of, say for example motor function. These and several other potential applications are the compelling factors that motivate us to develop a fully real-time analysis system for fMRI time series. In simple terms, the research’s goal is to see the activation map unfolds in time as the subject performs the designated task, thereby enabling us to look how the brain works in real time.

Fig. 2. The above schematic shows the computational flowchart of the real-time analysis of fMRI time series, which starts immediately after an image is acquired and ends after the statistical parametric map is updated. The steps are repeated when a new image data is acquired.

In order to achieve this goal, we need to overcome two main difficulties, namely: 1) the need for a general real-time parametric analysis tool and 2) the computational requirement. The former requires analysis tools that we can use in real-time to be able to process fMRI data in the same rigor as that of offline analysis methods, while the latter demands computational prowess that can cope up with the needed computations. To overcome the first problem, we develop an algorithm to estimate the coefficients of general linear model (GLM), a versatile tool for parametric analysis, using an orthogonalization procedure. The algorithm offers several advantages including incremental estimation, minimal use of memory during the estimation process, fixed computational cost for each estimate update, among others, making it highly suitable for real-time applications. Using this as the basis for general real-time parametric analysis, a real-time analysis system is developed. To achieve results of comparable quality to that obtained by offline processing methods, realignment for motion correction and smoothing operations are incorporated into the computational pipeline. To meet the computational demand, we employ inexpensive and economically viable cluster of personal computers or PC cluster. The result is the real-time fMRI analysis system schematically shown in Fig. 1.

Fig. 3. Real-time activation maps at different time steps (n = 30, 50, 70, 90, 110, and 130) of a slice containing the primary motor cortex.

The system is composed of an MR scanner subsystem for data acquisition and paradigm control, a computational server (a PC cluster) for real-time fMRI data analysis, and a storage device for storing data. For offline operation, the MR scanner subsystem sends data to the storage device where the computational server can access for future analysis. For real-time operation, the MR scanner subsystem sends the data directly to the computational server for immediate processing. With this system, we achieved a fully real-time analysis of high spatial resolution whole-brain fMRI time series. The analysis includes realignment, smoothing, GLM estimation, and statistics computation (Fig. 2). All computations were performed immediately after the acquisition of each image volume and completed within TR set to 3 s. Real-time activation maps at different times for a slice containing the primiary motor area are shown in Fig. 3.

The real-time analysis system is designed such that the computational server does not have to be in the same site as the MR scanner. The idea is for imaging facilities that do not have a dedicated computational facility to be able to use remote computing resources on demand. This means that when needed the MR scanner subsystem could connect to a remote computational server via a high speed network and still be able to perform the required real-time operations. One way to realize this is to employ GRID technology. This will be the next step we will be taking, that is, the development of GRID-enabled real-time fMRI analysis system. The motivation is to make imaging facilities real-time capable by simply connecting to the GRID.

 

When the virtual world merges with the real one

Thursday, November 3rd, 2011

Just want to share this YouTube video from MicrosoftResearch. It’s just amazing. The idea is to augment the real environment with a virtual one and interact with it. Using four ceiling-mounted Kinects, the entire room is mapped into a virtual 3D environment. Virtual objects can be placed in this virtual environment and projected into the real one using handheld projectors. The interaction is quite impressive.