Home > brain, matlab > Convert images to matrix

Convert images to matrix

September 2nd, 2010

Quite often you need to convert an image (or multiple images) to a MatLab matrix for further analysis and visualization (e.g. extracting time series, multivariate pattern analysis, etc). SPM provides handy functions for this:

P = spm_select; % select 1 or more images
V = spm_vol(P);
M = spm_read_vols(V);

The dimension of M is 3D or 4D depending on how many images you selected. The 1st 3 dimensions are spatial and the last one is temporal.

If you want to save a matrix to a image file, use

V.fname = 'b.img';%
spm_write_vol(V, M);
Author: Xu Cui Categories: brain, matlab Tags:
Try Stork, a research tool we developed

Stork is a publication alert app developed by us at Stanford. As a researcher we often forget to follow up important publications - and it's practically impossible to search many keywords or researchers' names everyday. Stork can help us to search everyday and notifies us when there are new publications/grants. How Stork helped me?

About the author:

Xu Cui is a human brain research scientist in Stanford University. He lives in the Bay Area in the United States. He is also the founder of Stork (smart publication alert app), PaperBox and BizGenius.


He was born in He'nan province, China. He received education in Beijing University(BS), University of Tennessee (Knoxville) (MS), Baylor College of Medicine (PhD) and Stanford University (PostDoc). Read more ...
  1. Abhishek
    May 17th, 2012 at 11:27 | #1

    i need to generate .mat file for ORL database(say). how to do it?also can i use the same .mat file in regression/classification?how to split database into predictor and response arrays (X & Y) for regression/classification.
    please provide suitable matlab functions.
    thank you

  2. Boureghda Mohammed
    December 10th, 2016 at 06:19 | #2

    How can I correct the order of images in the file used by spm_vol.

  3. December 10th, 2016 at 12:14 | #3

    @Boureghda Mohammed
    If I remember correctly, the order is actually correct.