• If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Stop wasting time looking for files and revisions. Connect your Gmail, DriveDropbox, and Slack accounts and in less than 2 minutes, Dokkio will automatically organize all your file attachments. Learn more and claim your free account.


Electrode Localization

Page history last edited by David Groppe 9 months, 1 week ago

Notation Key:

In this page, "$" indicates a command that should be run in your operating system's terminal window and ">>" indicates a Matlab command.You don't actually type the $ or >> when running the command. "*" represents a patient's FreeSurfer folder name (e.g., PT001).


Tutorial Data:

You can download the data used in the tutorial below from here. The data consists of a FreeSurfer folder for PT001. Place the PT001 folder in your FreeSurfer subjects directory and you should be able to run the commands below.



0. Overview

An overview of the electrode localization procedure: [A] FreeSurfer automatically segments a preimplant T1 MRI and constructs various brain surfaces. [B] Postimplant CT scan (red lines) is rigidly coregistered to the preimplant T1 MRI. [C] Postimplantation CT scan thresholded to highlight electrodes in BioImage Suite. [D] Electrodes manually identified in CT scan using BioImage Suite. Different colors correspond to different grids and strips of electrodes. [E] CT-based electrode locations overlaid on the pial surface derived from the preimplant MRI via FreeSurfer. Note that some electrodes do not lie on the surface of the brain due to postimplant brain shift.  [F] Electrode locations projected to the leptomeningeal surface to correct for brain shift using MATLAB.


1. Get a preimplant MRI of the patient without contrast

The MRI can be in dcm or nii format. A contrast agent is often injected into a patient before surgery and will make the MRI look something like this:


FreeSurfer CANNOT process contrast properly. You need a contrast-free MRI that should look something like this:




2. Have FreeSurfer process and automatically segment the preimplant MRI:

You do this with the recon-all command in your terminal window:

$recon-all -s PatientCodeName -i niiFileName -all -localGI


For example:

$recon-all -s PT001 -i /Users/penfield/Desktop/mri.nii.gz -all -localGI


Note that niiFileName could also be a dcm file in a folder that contains all the dcms for the MRI and that the localGI option requires Matlab. The localGI option creates a smoothed pial surface (a rough approximation of the leptomeningeal surface) that subdural electrodes will later be projected to in order to correct for postimplant brain shift.


The full recon-all procedure takes about 24 hours. After it finishes, visually check the accuracy of the automated segmentation by running something like the following command from the terminal:

$tkmedit PT001 T1.mgz -aseg -surfs


When the GUI pops up, the different brain regions are color coded, the pial surface is red and white matter surface is yellow. You can move through slices with the up/down arrow keys.


To visually check the accuracy of the pial surface you can run something like the following commands from the terminal:

$tksurfer PT001 lh pial

$tksurfer PT001 rh pial



When the GUI pops up, use the arrow buttons to rotate the brain to different views.


Unless the patient has an MRI abnormality (e.g., a tumor) or the MRI is poor quality, you should not have any serious errors in the automated segmentation. However, you should always check.


Finally, if you ran recon-all and everything completed save for the pial surface smoothing, you can run just that step with the following command:  

$recon-all -s subjid -localGI


For example:

$recon-all -s PT001 -localGI



3. Co-register the post-implant CT or MRI scan to the pre-implant MRI:

If using a postimplant CT scan, run something like the command below (substitute your patient's codename for PT001):

$ct2mri.sh PT001 /Users/penfield/Desktop/PT001_CT.nii.gz


If using a postimplant MRI scan, use mri2mri.sh instead:

$mri2mri.sh PT001 /Users/penfield/Desktop/PT001_postImp.nii.gz


The second argument is the nii.gz file of the postimplant CT or T1 MRI scan that you need to create with something like FSL's mri_convert function or Matlab's http://www.mathworks.com/matlabcentral/fileexchange/42997-dicom-to-nifti-converter (the iELVis repo actually contains a slightly modified version of that code). This script uses FSL's flirt command to rigidly (i.e., 6 degrees of freedom affine mapping) transform the CT scan so that it lines up with the preimplant MRI by maximizing the mutual information between the volumes. If you are using a postimplant MRI, the volumes are aligned by attempting to maximize the normalized correlation between volumes.


Images of the two volumes overlayed are automatically generated so that you can inspect the quality of the coregistration. In the process the elec_recon subfolder in the patient's FreeSurfer folder is created along with the following files:

  • T1.nii.gz: The full head MRI
  • brainmask.nii.gz: The skull stripped MRI
  • postimpRaw.nii.gz: The raw post-implant CT or MRI
  • postInPre.nii.gz: The post-implant CT or MRI coregistered to the pre-implant MRI


If these  scripts fail, try the scripts below instead:


These do the same thing ct2mri.sh and mri2mri.sh but use FreeSurfer's bbregister tool instead of FSL's flirt. Bbregister attempts to align the boundaries between tissue types:

$ct2mriBbreg.sh PT001 /Users/penfield/Desktop/PT001_CT.nii.gz

$mri2mriBbreg.sh PT001 /Users/penfield/Desktop/PT001_postImp.nii.gz


This use FSL's flirt to coregister the postimplant CT to the preimplant T1 by using the skull-stripped T1:

$ct2mriBmask.sh PT001 /Users/penfield/Desktop/PT001_CT.nii.gz


This is the same as ct2mri.sh but it does not search for good initial conditions to start optimization. It is faster and sometime works better:

$ct2mriFast.sh PT001 /Users/penfield/Desktop/PT001_CT.nii.gz


If all of those scripts fail, you can manually adjust the coregistration via the instructions here:

Manual Coregistration Adjustment


Images like the ones below are also generated so that you can check coregistration success. In this image, edges in the coregistered CT scan are shown over the T1 mri.


Copies of these images are stored in the elec_recon/PICS/COREG folder.


Note that if you have a postimplant CT and MRI you can use the script ct2mri2mri.sh to align the postimplant CT scan to the preimplant MRI by using the postimplant MRI as an intermediary volume. Some of us have found that this sometimes works better than just aligning the postimplant CT directly to the preimplant MRI.



4. Use BioImage Suite to localize electrodes in the  coregistered CT scan:


Here is a short video demo of how to use BioImage Suite to identify electrode locations in a CT scan once it has been aligned to the preimplant MRI. It's quite easy (despite all the instructions below).

  1. Start BioImage Suite (see their manual for how to do this for your operating system: http://www.bioimagesuite.org/doc/bioimagesuite_manual.pdf ).
  2. In the menu that pops up, click the Editors tab on the left and then select Electrode Editor in the new main menu that appears. Two new windows will pop up. The Electrode Editor window is for viewing neuroimaging files (your CT and MR) and the Electrode Control window is for creating the *.mgrid text file that indicates where electrodes are.
  3. In the Electrode Editor window, load postInPre.nii.gz file via the File menu. If using a CT scan, go to the Electrode Editor window and change view from 3-slice mode to 3D only (upper button) & 3-slice to Volume (below and left) to see the CT scan as 3D volume instead of slices. At first you will just see the CT scan as a block or cylinder because it is filling in every voxel. If using a postimplant MRI, select a 2D view (e.g., "Axial only").
  4. If using a CT scan, in the Electrode Editor window, click on Image Processing->Threshold and a new threshold window will pop up. Enter something like 5000 as the low threshold and something like 15000 or 20000 as the high threshold as default values. The best threshold value may depending on your CT scanner and particular data set. Now you should see the electrodes (and maybe teeth and wires). You may need to play with these thresholds a bit to improve the definition of electrodes (especially for electrodes that are almost overlapping). If electrodes look pixilated, try raising the upper limit.
  5. In the Electrode Control window, under the Patient Info tab, you can add or delete sets of electrodes. By default, it starts with an 8x8 grid. In the Electrode Control window, under the Electrode Info tab you can edit the properties of sets of electrodes. Probably the only two fields you need to edit are Grid Name and and Dimensions. When naming the set of electrodes, be sure to use the naming conventions described below (see CRITICAL!) so the name indicates the electrode type and hemisphere. Once you change any of these properties, hit the Update Grid button and indicate Yes in the pop up dialogue box.
  6. To be able to start assigning electrodes to the postimplant CT  or MRI, activate Button Pick and press Pick Current in the lower right corner of the Electrode Info tab on the Electrode Control window. You also need to switch to Full Edit Mode under the Edit menu of the Electrode Control window. Change the color of the set of electrodes to something unique and easy to see via Grid->Grid Color on the Electrode Control window menu.
  7. To assign a particular electrode to a blob in the postimplant scan, select that electrode in the Electrode Arrangement section of the Electrode Control window. Under Electrode Properties the Grid/Electrode line will tell you the number of the set of electrodes (i.e., strip or grid; indexing starts with 0) and the number of the electrode in that set that you've selected (indexing starts with 1). Hold down "shift" and left click on the electrode in the CT/MRI scan. You may need to hold down the mouse button for a bit. A colored sphere or circle should appear where you're pointing. If it doesn't seem to work, switch to another electrode in that grid/strip/depth and come back to it.
  8. If you're not happy with the localization in a 3D CT scan try changing Volume Trace to a lower value (default=10) via the Volume Trace menu in the Electrode Control window. This parameter specifies the size of the sphere (I believe it defines the diameter in mm) around the mouse pointer that is averaged over to determine the center of mass where the electrode is placed. Smaller values means the electrode center will be closer to where the mouse is located. Raising the CT threshold may also help as faint above threshold voxels may capture the electrode. Raising the CT scan threshold can also help as some voxels with low CT signal may not be visible to your eye, but will pull the electrode off center. I do not think Volume Trace has any effect when indicating electrode locations in 2D slices.
  9. When you're done identifying all the electrodes, save the locations to a text file via the File->Save menu on the Electrode Control window. Call it *.mgrid where * is the patient's codename (e.g., PT001.mgrid). Note, that BioImage Suite automatically saves your results as you working in an *autosave.mgrid file.

Electrode Naming Conventions (CRITICAL!)

iELVis Matlab functions expect the mgrid file electrode names to obey the following conventions:

  • Start each electrode name with RD_, RS_, RG_, LD_, LS, or LG_ followed by the name of the electrode (e.g., RD_RHD). The first letter indicates which hemisphere the electrode lies in and the second letter indicates if the electrode is a depth, subdural strip, or subdural grid electrode. For example, RD_RHD might be a name of right hemisphere hippocampal depth electrode and LG_Grid might be a name of left hemisphere grid of subdural electrodes.
  • Do NOT put spaces or additional underscores in the names of the electrodes


BioImage Suite Visualization Tips:

  • You can select how many sets of electrodes to view (one, all, a subset) via the Display menu of the Electrode Control window.
  • It can be helpful to use the Volume button on the Electrode Editor window to selectively hide parts of the CT scan
  • You can get rid of the green box around the CT scan with the Box menu on the Electrode Editor window
  • To view electrodes on the MRI, load the MRI nii file via the File menu of the Electrode Editor window
  • The right Zoom arrow on the Electrode Editor window zooms in, the left zooms out.
  • Rotate the image in the Electrode Editor window by clicking and moving your mouse on the image
  • Click the Reset button on the Electrode Editor window to return to default viewing angle and scale
  • Export the CT/MRI image to disk with the Save Snapshot button on the Electrode Editor window
  • You can also label electrode locations in 2D slice views. This is necessary for labeling electrodes in postimplant MRIs and useful for electrodes that show up only weakly in the CT.
  • If it is difficult to label to label all the electrodes in a CT scan (due to poor CT resolution or small electrodes/electrode spacing), you can label 3 contacts and then select menu Grid > Auto Warp. BioimageSuite will then fit a spline through the points, positioning all the other electrodes along the shaft automatically. This has the advantage of "smoothing" the electrode as compared to manually clicking on every artifact.


Electrode Numbering Tips

  • For strips and depths, the electrode furthest from the opening in the skull is #1.
  • To see the numbers of the electrodes in the Electrode Editor window, select a non-zero fontsize in the Labels menu of the Electrode Control window.


Electrode Coloring Conventions

  • Try to give each electrode a unique color. Use colors that will show up well on the MRI. Thus, it is best to avoid gray scale colors. It is best to use bright (e.g., neon) colors for depths.


Electrode Tagging Tips

  • If you place 3 contacts (including 1st and last) satisfactorily along a depth or strip electrode, you can use the menu Grid > Auto Warp and BioimageSuite will automatically position all the other electrodes based on the inter-electrode distances.



5. Export mgrid information to simple text files and correct for postimplant brain shift:

The electrode coordinates in the mgrid file you created need to be exported to simple text files and converted to a few different coordinate systems for plotting. We do this with one of the following two sets of functions that also correct subdural electrode locations for postimplant brain shift. Depth electrode coordinates are not corrected for brain shift.


Downloading/setting up all the MATLAB code below is described here: Installing iELVis


Method A: Yang, Wang et al. (2011)

1. Make *PostimpLoc.txt in patient's elec_recon folder:



2. Make multiple coordinate files (including coordinates corrected for brain shift):



Note, if you are running yangWangElecPjct.m on PT001, when asked about the grid size and numbering just hit return to accept the default values. Note also that yangWangElecPjct.m uses some functions in the MATLAB Statistics and Machine Learning toolbox, which is not installed by default when you purchase MATLAB. Also note that this method does NOT work on grids placed over medial brain areas (e.g., an interhemispheric grid). To use this method on such grids, simply relabel the grids as strips in the BioImage Suite mgrid file.


Method B: Dykstra et al. (2011)

1. Make multiple coordinate files (including coordinates corrected for brain shift):



Note that dykstraElecPjct.m uses some functions in the MATLAB Optimization toolbox and Statistics and Machine Learning toolbox, which are not installed by default when you purchase MATLAB. If you do not have these functions, you can still use a simplified version of dykstraElecPjct.m by setting its minimizeChange parameter to 0.


Both methods produce the following files in the elec_recon subfolder:

  • PT001.POSTIMPLANT: The RAS coordinates of electrodes before any correction for postimplant brain shift in units of mm. This was originally called PT001.CT.
  • PT001.LEPTO: The leptomeningeal surface RAS coordinates of electrodes after correction for postimplant brain shift in units of mm. Depth electrode coordinates are the same as in *.POSTIMPLANT.
  • PT001.LEPTOVOX: The leptomeningeal surface voxel coordinates of electrodes after correction for postimplant brain shift. Voxel coordinates are for brainmask.nii.gz file also in the elec_recon folder. Depth electrode coordinates are the same as in *.POSTIMPLANT.
  • PT001.INF: The pial RAS coordinates of electrodes on the inflated pial surface in units of mm after correcting for brain shift. Depths have NaN coordinates.
  • PT001.PIAL: The pial surface RAS coordinates of electrodes in units of mm after correction for postimplant brain shift. Depth electrode coordinates are the same as in *.POSTIMPLANT.
  • PT001.PIALVOX: The pial surface voxel coordinates of electrodes after correction for postimplant brain shift. Voxel coordinates are for brainmask.nii.gz file also in the elec_recon folder. Depth electrode coordinates are the same as in *.POSTIMPLANT.
  • PT001.electrodeNames: A text file that indicates the name, type of electrode (strip, grid, depth), and hemisphere in which each electrode lies. The ith row of this file corresponds to the ith row of coordinate files.


They also make plots like these that illustrate how far electrodes were moved to correct for brain shift:


Note that you can click on the electrodes/circles in these plots to see the name of the electrode it corresponds to. A jpg of this figure is output by default to the elec_recon/PICS subfolder.


For more information on these methods see: Brainshift Correction Methods



6. Create images of electrode locations:

Run the following iELVis MATLAB functions to create images of the electrode locations.


For subdural electrodes:



...you'll get images like this:



For depth electrodes:

>>cfg=[]; cfg.printFigs=1;



...you'll get images like this:


These functions automatically output those figures as jpg files in the elec_recon/PICS folder.


If you use the anatOverlay option of plotAllDepthsOnSlices.m, FreeSurfer's anatomical segmentation is overlayed in color over the MRI like this:





If using FreeSurfer, cite:


Or if pressed for space, this link is probably more important:


If using FSL's FLIRT, cite:

  • Jenkinson, M., Smith, S., 2001. A global optimisation method for robust affine registration of brain images. Med. Image Anal. 5 (2), 143–156. http://dx.doi.org/10.1016/S1361-8415(01)00036-6.
  • Jenkinson, M., Bannister, P., Brady, J. M. and Smith, S. M. 2002. Improved Optimisation for the Robust and Accurate Linear Registration and Motion Correction of Brain Images. NeuroImage, 17(2), 825-841.


If using FreeSurfer's bbregister, cite:

  • Greve, D.N. and Fischl, B. Accurate and robust brain image alignment using boundary-based registration. NeuroImage, 48(1):63-72, 2009.


If using BioImage Suite, cite:

  • Joshi, A., Scheinost, D., Okuda, H., Belhachemi, D., Murphy, I., Staib, L. H., & Papademetris, X. (2011). Unified framework for development, deployment and robust testing of neuroimaging algorithms. Neuroinformatics, 9(1), 69-84. 


If using the Yang, Wang, et al. method for correcting for brainshift, cite:

  • Yang, A. I., Wang, X., Doyle, W. K., Halgren, E., Carlson, C., Belcher, T. L., et al. (2012). Localization of dense intracranial electrode arrays using magnetic resonance imaging. NeuroImage 63(1), 157–165. doi:10.1016/j.neuroimage.2012.06.039


If using the Dykstra et al. method for correcting for brainshift, cite:

  • Dykstra, A.R., Chan, A.M., Quinn, B.T., Zepeda, R., Keller, C.J., Cormier, J., Madsen, J.R., Eskandar, E.N., Cash, S.S., 2011. Individualized localization and cortical surface-based registration of intracranial electrodes. NeuroImage 1–42.


Comments (0)

You don't have permission to comment on this page.