Search code examples
matlabfilepngformat-conversion

How to convert multiple .png files to .mat files


spatial data (.png)

001.png
002.png
003.png
.
.
.
00n.png

to

001.mat
002.mat
003.mat
.
.
.
00n.mat

Solution

  • Complementing the answer of EitanT, if you have files which does not have such filename restrictions, such as:

    file01.png
    file02.png
    fls1.png
    fls2.png
    pics001.png
    pics002.png
    

    You can use dir function, which gives you more flexibility. For example:

    filenames = dir('*.png'); %# get information of all .png files in work dir
    n  = numel(filenames);    %# number of .png files
    
    for i = 1:n
        A = imread( filenames(i).name );
    
        %# gets full path, filename radical and extension
        [fpath radical ext] = fileparts( filenames(i).name ); 
    
        save([radical '.mat'], 'A');                          
    end
    

    fileparts is a MATLAB function which decomposes the filename in file path, radical and extension. E.g., if I have the file /home/user/photo.png, this function will return:

    fpath   = /home/user
    radical = photo
    ext     = .png
    

    File format error

    OP got the following error:

    ??? Error using ==> imread at 387 Unable to determine the file format. Error in ==> PNG2MATFiles at 5 A = imread( filenames(i).name );

    I've download his original *.png images and tested them with file linux command. My output:

    FY2E_2011_09_01_00_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_01_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_02_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_03_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_04_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_05_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_06_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_07_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_08_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_09_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100 FY2E_2011_09_01_10_01_ir1_proj.png: Matlab v5 mat-file (little endian) version 0x0100

    imread can't open these files as 'png' because they are already stored as .mat.