eXTReMe Tracker
Sep 122016
 

There is good news for those who use neuroimaging tools such as AFNI, FSL and FreeSurfer on their Windows machines. The limitation is that they can only be run on Windows 10 with anniversary update. Does it use a Virtual Machine? No. It runs “natively” on Windows 10, so you can save, print, resize or hide any interface just like a Windows program.

Freeview running in Windows 10

Freesurfer on Windows 10

Before I get into how to install FreeSurfer, I must thank the author at K-Lab for the post on “How to run FSL on Windows 10“. That post describes how to install BASH on Windows 10 in the first few steps. Sadly it is not available for Windows 7/8. It uses Ubuntu 14.04 LTS which will be supported by Canonical until 2019. We hope by then Windows would incorporate the Ubuntu 16.04 LTS as the default distribution.

I’ll repeat a few things (steps 1-5) that Lin4Neuro wrote on how to get BASH and X-server on Windows 10.

  1. Install Linux BASH shell on Windows 10:
    There is detailed tutorial with screenshots on how to do this at the following site.
    How to Install and Use the Linux Bash Shell on Windows 10
  2. Install the updates:
    Before adding any tools, you should first download and install the updates for Ubuntu. Run the following commands at the terminal

    sudo apt-get update
    sudo apt-get upgrade
  3. Install the X server:
    Installing BASH will allow you to run applications on a command line but in order to run any GUIs for neuroimaging tools you require a X-server for windows. The most popular software for this is Xming. You can download and install it with default settings.
    Xming X server for Windows
  4. Running X server:
    Run Xming by searching it from start menu. When it is loaded you should see this when you go to show hidden icons button at the bottom right corner of your desktop.
    xming_server
  5. In order for X server to work with BASH run the following command at the terminal
    echo "export DISPLAY=localhost:0.0" >> ~/.bashrc

    This will add the environment variable for display to the .bashrc file.


  6. Downloading Freesurfer:
    You can obtain your copy of Freesurfer from their web page. I would recommend getting the nightly build as I was having some trouble running the stable version v5.30, especially some of the graphical windows. If you want to try the stable version download the 64-bit centos6 stable v5.3.0 freesurfer. I would encourage getting the v6.0 nightly build even though it is not the official release. You can go back and reinstall the stable version 6.0 once it is released.To download your choice of FreeSurfer type this command at the terminal:
    For stable release v5.3.0

    ftp://surfer.nmr.mgh.harvard.edu/pub/dist/freesurfer/5.3.0/freesurfer-Linux-centos6_x86_64-stable-pub-v5.3.0.tar.gz

    For nightly build

    wget ftp://surfer.nmr.mgh.harvard.edu/pub/dist/freesurfer/dev/freesurfer-Linux-centos6_x86_64-dev.tar.gz

    Hint: You can copy the link with your mouse and when you right-click at the terminal, it will be automatically pasted so you don’t have to type it in manually.
    This is a large file (~4.6GB) so it may take some time to download it based on your network speed.

  7.  Extract the zipped file to install it. It is customary to install it at /usr/local/ so let’s extract it to that directory.
    sudo tar -xzf freesurfer-Linux-centos6_x86_64-dev.tar.gz -C /usr/local/

    You will require your admin password (for Linux) to extract it to /usr/local. Again this step can take few minutes since it is extracting a file that’s several gigabytes in size. Once extracted, we’ll have to change permissions on that folder.

    sudo chmod -R 755 /usr/local/freesurfer

    This allows you to make changes to files in that folder.

  8. Obtain the FreeSurfer license:
    In order to run the FreeSurfer applications you need to register and obtain a license from their website.
    FreeSurfer Registration
    Once you have the license emailed to you, copy the contents between the lines that read “cut here” and create a license.txt file.

    sudo nano /usr/local/freesurfer/license.txt

    fs_lic
    Paste the contents with right-click
    Press ctrl+X to exit
    Press y to accept and save it as license.txt
    Hit Enter

  9. Add FreeSurfer path to .bashrc:
    echo "export FREESURFER_HOME=/usr/local/freesurfer" >> ~/.bashrc
    echo "source \$FREESURFER_HOME/SetUpFreeSurfer.sh" >> ~/.bashrc
  10. Dependencies: libjpeg.so.62
    Generally there is a libjpeg dependency that is required by FreeSurfer graphics. It doesn’t come with the basic Ubuntu installation but it can be installed using:

    sudo apt-get install libjpeg62
  11. Final check:
    Check that the Xming server is running and it says Xming Server:0.0 when you hover the mouse on the icon in the lower right hand corner.Type bash at the terminal. You should see the following:

    -------- freesurfer-Linux-centos6_x86_6.0 --------
    Setting up environment for FreeSurfer/FS-FAST (and FSL)
    FREESURFER_HOME   /usr/local/freesurfer
    FSFAST_HOME       /usr/local/freesurfer/fsfast
    FSF_OUTPUT_FORMAT nii.gz
    SUBJECTS_DIR      /usr/local/freesurfer/subjects
    MNI_DIR           /usr/local/freesurfer/mni
  12. Test your installation:
    Check if everything works by going through some of the examples listed on the FreeSurfer website.
    FreeSurfer examples
    If everything has been installed correctly you should be able to run command line functions and open GUIs just like on a Mac or Linux machine.
    tksurfer_win10If you have any questions about the installation, please post a comment. If you have questions about FreeSurfer please visit the FreeSurfer user community mail archives.
Dec 222014
 

The purpose is to to convert a 3-dimensional image file which contains X,Y and the dimensions containing RGB values to a 2D image file in grayscale. It can be done in linux command line using imagemagick.

convert <img_in> -set colorspace Gray -separate -average <img_out>

The resulting image is a 2D image generated by averaging the R,G,B arrays.

Dec 152014
 

Converting nifti files to dicom using nifti toolbox in matlab

clear; clc;
 addpath('/usr/local/matlab/toolbox/niftitools');
 subjectdir='/media/storage/SPECT_mapping/bbobby';
 cd(subjectdir);
 [dicomfile, dicompath] = uigetfile('*.dcm','Select DICOM header for metadata');
 metadata = dicominfo(fullfile(dicompath, dicomfile));
 metadataISAS=metadata; metadataMPR=metadata; metadataFUS=metadata;
 
 metadataMPR.SeriesDescription = 'SAG_MPRAGE_T1_Recon'; metadataMPR.SeriesNumber = 1;
 metadataISAS.SeriesDescription = 'ISAS Hyperperfusion'; metadataISAS.SeriesNumber = 2;
 metadataFUS.SeriesDescription = 'MPRAGE ISAS Fusion'; metadataFUS.SeriesNumber = 3;
 
 cd(subjectdir);
 isas = uigetfile('hyper*.nii','Select hyperpefusion file');
 structural = uigetfile('mprage*.nii','Select MPRAGE');
 
 isas = load_untouch_nii(isas); isas = isas.img; isas = int16(isas);
 structural = load_untouch_nii(structural); structural = structural.img;
 
 display('... Merging Hyperperfusion and MPRAGE');
 
 merged = structural;
 merged(isas>0) = max(max(max(structural)))+10;
 
 display('... Finished Merging')
 
 isasdir = fullfile(subjectdir,'isas');
 if exist(isasdir) ~= 7
     mkdir(isasdir);
     mkdir(fullfile(isasdir,'SPECT_ISAS')); spectdir = fullfile(isasdir,'SPECT_ISAS');
     mkdir(fullfile(isasdir,'structural')); structdir = fullfile(isasdir,'structural');
     mkdir(fullfile(isasdir,'fusion')); fusiondir = fullfile(isasdir,'fusion');
 end
 
 cd(isasdir);
 
 % dicomwrite(reshape(x4,[170,256,1,256]), 'SPECT_ISAS.dcm', metadata, 'CreateMode', 'copy');
 display('... Creating DICOMS');
 
 for slicenum = 1:size(isas,1)
     
     cd(spectdir); metadataISAS.InstanceNumber = slicenum;
     dicomwrite(fliplr(rot90(squeeze(isas(slicenum,:,:)))), sprintf('SPECT_ISAS_%03d.dcm',slicenum), metadataISAS, 'CreateMode', 'copy');
     
     cd(structdir); metadataMPR.InstanceNumber = slicenum;
     dicomwrite(fliplr(rot90(squeeze(structural(slicenum,:,:)))), sprintf('structural_%03d.dcm',slicenum), metadataMPR, 'CreateMode', 'copy');
     
     cd(fusiondir); metadataFUS.InstanceNumber = slicenum;
     dicomwrite(fliplr(rot90(squeeze(merged(slicenum,:,:)))), sprintf('FUSION_MPR_ISAS_%03d.dcm',slicenum), metadataFUS, 'CreateMode', 'copy');
     
     display(sprintf('... Creating slice %d',slicenum))
 end
 
 cd(subjectdir);
Oct 232014
 

To compute a transpose of an input file, i.e. converting columns to rows and rows to column using bash, you can accomplish that using awk and while loop.

#!/bin/bash
cols=`cat $1 | head -1 | wc -w`;
for i in $(seq 1 $cols);
do
awk -v "n=$i" '{print $n}' $1 | tr '\n' ' ';  # variable column output
printf "\n";
done

This example uses a variable to output a specific column from the input.

awk -v "n=$variable" '{print $n} ' input.txt

Will pass the variable to n and the nth column gets printed from input file.

Oct 242012
 

1. Convert the brain.mgz volume to analyze:

mri_convert $SUBJECTS_DIR/bert/mri/brain.mgz brain.img

2. Align brain.img with your functional data in spm (eg, func.img)

3. Create your spm statistical output (eg, t.img)

4. Create the registration file:

tkregister2 --s subjectname --mov meanswaf.img --regheader --reg  register.dat --surf orig

This will bring up the tkregister window with the orig volume. Hit the “Compare” button to see the functional. The green line will be the surface. Make sure the alignment is good (ie, the green line follows the bright intensity patterns in the functional). Hit the “Save” button to save the registration. This will create a file called register.dat. If you make modifications to the registration and then want to view or edit it later, re-run the above command WITHOUT –regheader. This requires a lot of manual tweaking to get the functional brain aligned with Bert brain.

5. View your functional data in the volume:

tkmedit subjectname orig.mgz -overlay spmT_0001.img -overlay-reg register.dat

6. View your functional data on the surface:

tksurfer subjectname lh inflated -overlay spmT_0001.img -overlay-reg register.dat

Adopted from spmPainting

Sep 192012
 
Simple image compression algorithm using plain FFT computation

FFT2 based image compression

Test code to generate a circular mask that removes the low frequency components from an image.

Step through radius to get the percentage compression.

IM=imread('images_01.jpg');IM=IM(:,:,2); %Select a channel
%
cx=size(IM,2)/2; cy=size(IM,1)/2;
ix=size(IM,2);iy=size(IM,1);r=833;
[x,y]=meshgrid(-(cx-1):(ix-cx),-(cy-1):(iy-cy));
c_mask=((x.^2+y.^2)>r^2);
%
filtIM = fft2(IM).*c_mask;
filtIM = ifft2(filtIM);
IM2=abs(double(IM)-abs(filtIM));
%
x=size(IM,1)*size(IM,2); y=size(find(c_mask==1)); y=y(1);
res=y/x*100;
%
figure(1); 
subplot(2,2,1); imshow(c_mask);
subplot(2,2,2); imagesc(IM2); axis image; axis off;
subplot(2,2,3); imshow(IM); title('Origianl image');
subplot(2,2,4); imagesc(abs(filtIM)); axis image; axis off;
title(sprintf('Percent original: %0.2f',res));
Nov 162011
 

On most Linux/Unix based systems, you can save your Matlab figure as a postscript instead of saving it as a png or jpg. One advantage of saving figures in this manner is that you can save multiple images as separate pages on that .ps document, whereas with png/jpg you have to save each image as a separate file.

To print the current image to postscript, all you need to run is:

print(‘-dpsc2′,’filename’);

To have multiple images appended within the postscript document, you need to use the -append switch.

print(‘-dpsc2’, ‘-append’, ‘filename’);

Your output postscript will have the name filename.ps

To convert the postscripts to pdf format, just run the ps2pdf command in the terminal window:

ps2fpdf filename.ps

The output of this would be filename.pdf

And you’re done.

Apr 142011
 

Assuming the nifti toolbox is in Matlab path, we can get the 91x109x91 mask to have the same dimensions as the normalized images generated with bounding boxes.

If we are making a mask for hippocampus, first we save that mask from WFU Pickatlas. Then to make it 79x95x68 voxels, run the following small script.

x=load_untouch_nii(‘hipp.img’);
x=x.img;xdim=[1:6 86:91]; ydim=[1:6 102:109]; zdim=[1:11 80:91];
origin=[40 57 26]; datatype=16;
x(xdim,:,:)=[]; x(:,ydim,:)=[]; x(:,:,zdim)=[];
nii=make_nii(x, [2 2 2], origin, datatype);
save_nii(nii, ‘boxedhippo.nii’)

We can then use these masks for signal extraction or any further processing.

Mar 302011
 

FSL: flirt is used to compute an intial affine normalization of the T1 weighted images; this is then fed to fnirt to compute the overall transformation. flirt is also used to register the EPI’s to the subject’s structural image. This was then used along with fnirt-s warp in applywarp to normalize the EPIs.

Script for normalizing the T1-weighted structurals to the template:

Registering T1-structural to MNI152
bet my_structural my_betted_structural
 flirt -ref ${FSLDIR}/data/standard/MNI152_T1_2mm_brain -in my_betted_structural -omat my_affine_transf.mat
 fnirt --in=my_structural --aff=my_affine_transf.mat --cout=my_nonlinear_transf --config=T1_2_MNI152_2mm
 applywarp --ref=${FSLDIR}/data/standard/MNI152_T1_2mm --in=my_structural --warp=my_nonlinear_transf --out=my_warped_structural

Registering functional data to MNI152 (via structural scan)

bet my_structural my_betted_structural
 flirt -ref my_betted_structural -in my_functional -dof 7 -omat func2struct.mat
 flirt -ref ${FSLDIR}/data/standard/MNI152_T1_2mm_brain -in my_betted_structural -omat my_affine_transf.mat
 fnirt --in=my_structural --aff=my_affine_transf.mat --cout=my_nonlinear_transf --config=T1_2_MNI152_2mm
 applywarp --ref=${FSLDIR}/data/standard/MNI152_T1_2mm --in=my_functional --warp=my_nonlinear_transf --premat=func2struct.mat --out=my_warped_functional
Mar 142011
 
#!/bin/bash
 #$x would be the input filename and %3d will pad it to be a 3 digit number with zero pads, %4d will make it 4 digit and so on.
 num=`expr match "$x" '[^0-9]*\([0-9]\+\).*'`
 paddednum=`printf "%03d" $num`
 echo $paddednum
Dec 012010
 

Script to preprocess 4D fMRI time series:

spm_defaults;
 global defaults;
%% Slice Timing
display('Step 1: Slice Timing');
sliceorder = [1:2:17 2:2:16];
 refslice = 17;
 TR = 1;
 precision = 5;
 nslices = length(sliceorder);
P = dir('4Dout*.nii');
 P = char(P.name);
 TA = TR - TR/nslices;
if precision > 0
 TAstr = num2str(TA, precision);
 TA = str2double(TAstr);
 end
timing(1) = TA / (nslices -1);
 timing(2) = TR - TA;
 spm_slice_timing(P, sliceorder, refslice, timing);
%% Realignment and Reslicing
display('Step 2: Realignment');
 P=dir('a4Dout*.nii');
 P=char(P.name);
 FlagsC = struct('quality',1,'fwhm',5,'rtm',1,'interp',1);   %Flags for realignment
 spm_realign(P,FlagsC);
display('Step 3: Reslice');
 %Flags for reslicing
 FlagsR = struct('mask', 1, 'mean', 1,'interp',4,'which',0, 'wrap', defaults.realign.write.wrap);
 spm_reslice(P,FlagsR);
 display('... saving motion parameters as a motion_report.pdf ');
 saveas(gcf, 'motion_report', 'pdf');
 close all;
%% Normalization
display('Step 4: Normalization');
template = fullfile(spm('Dir'),'templates', 'EPI.nii');
 srcimage = 'mean*.nii';
meanimg = dir(srcimage);
 P = char(meanimg.name);
 snmat_name = strrep(P, '.nii', '_sn.mat');
 if exist(snmat_name, 'file')
 disp(['... removing existing file named: ' snmat_name]);
 delete(snmat_name);
 end
 objmask_name = '';
spm_normalise(template, P, snmat_name, defaults.normalise.estimate.weight, objmask_name,defaults.normalise.estimate);
%% Write Normalized Images
display('Step 5: Writing Normalized Images');
PP = dir('a4D*.nii');
 PP = char(PP.name);
 spm_write_sn(PP, snmat_name, defaults.normalise.write);
%% Smoothing
display('Step 6: Smoothing ... ');
PP = dir('wa4D*.nii');
 PP = char(PP.name);
 PP = cellstr(PP);
for list = 1:length(PP)
 Q = strcat('s', PP{list});
 spm_smooth(PP{list}, Q, defaults.smooth.fwhm);
 end
 %display(sprintf('\nPreprocessing compled.\n\nTime taken %d sec.\n', x));
Getting data extracted from time series:
Create ROI maps with WFU Pickatlas and MarsBar.
 Extract the contents of masks by:
 XYZ=struct(roi); XYZ=XYZ.XYZ;
%% Convert XYZ to mm
XYZ=[XYZ; ones(1, size(XYZ,2))]; XYZmm=roi.mat*XYZ; XYZmm(end,:)=[];XYZmm=XYZmm';
%%
p=spm_vol('swaf00xx.nii');
 [time_data]=spm_get_data(p, XYZ);
 time_data=mean(time_data,2);
Mar 082010
 

In order to convert files in .img and .hdr format to a single .nii file, we first need to install the nifti tools toolbox for matlab.

nifti tools

Once the path for nifti tools has been set in matlab, the files in .hdr and .img format can be combined to create a .nii file by running the following two commands:

nii=load_nii(‘filename_with_hdr_extension’);
save_nii(nii, ‘desired_filename_for_niftifile.nii’);

If you have freesurfer installed, you can convert between the files types with mri_convert by specifying the input (-it) and the output (-ot) type.

mri_convert -i name_of_input_file -it nifti1 -ot nii -o name_of_output_file

If you have functional dataset with several volumes over the course of your experiment, you can use the fslmerge function available in FSL to combine all the nifti files into a single 4D file.

fslmerge -t output_name.nii *.nii

Where *.nii would cover the entire set of nifti files if they are arranged sequentially.

Its not required to type in the extension .hdr or .img for the input image or output image if you have specified the input and the output types. By specifying the input type of nifti1, you tell the program that it will be a .hdr/.img pair, and specifying output type as nii goes for having your output with .nii extension.

To gzip the nifti file for use in freesurfer:

gzip filename.nii filename1.nii.gz

This will create a gzipped nifti file.

To automatically segment the structural volume:

recon_all -i filename1.nii.gz -subjid SUBJID -all

This will segment the structures containing in the structural file filename.nii.gz. Complete information on using recon-all for freesurfer can be found at FreeSurfer Wiki.

For some reason, Freesurfer seems to work well in tcsh. I’ve often encountered problems of weird nature when running it under bash. In order to run your autosegmentation with freesurfer type in tcsh at the terminal, since by default it is set to bash in most linux distros.