images2ENVI.m 2.56 KB
function images2ENVI( image_struct, filename )
%HSIWRITE : This function generates a hyperspectral binary image and header
% based on multi-dimention image
%
%
% This function accepts a srutcture which contains several channels.
% It creates a 'bsq' interleaved image and a ENVI header filer correspoing
% to the information of the image

fields = fieldnames(image_struct);

% check all images to have the same size
for i = 1 : size (fields, 1)
    for j = 1 : size (fields, 1)
        if size(image_struct.(fields{i}))~= size(image_struct.(fields{i}))
            fprintf ('Dimension of input images do not Match !');
            exit;
        end
    end
end





% Extracting the needed information
base_image = image_struct.(fields{1});

rows = size(base_image, 1);
columns = size(base_image, 2);
bands = size(fields,1);
multiDimImage = base_image';                                                % Matlab stores column major, transposing make it row major to be saved on memory

% Create multi-dimentional image
for j = 1 : size(fields,1)
    multiDimImage(:,:,j) = (image_struct.(fields{j})');                     % Matlab stores column major, transposing make it row major to be saved on memory
end

% create the binary image
HSImage = reshape (multiDimImage, [rows*columns*bands, 1]);
if (~isfloat(HSImage))
    HSImage_float = single(HSImage);                                         % casting to float
end
multibandwrite(HSImage_float,filename,'bsq');


% create the header file
info.samples = columns;
info.lines = rows;
info.bands = bands;
info.header_offset = 0;
info.file_type = 'ENVI Standard';
info.data_type = 4;
info.interleave = 'bsq';




fid = fopen(strcat(filename, '.hdr'),'w');                                  % open a file to write the header file
fprintf(fid,'%s\n','ENVI');                                                 % first line of the header file showing it is an ENVI file

info_fields=fieldnames(info);
for i = 1:length(info_fields)
    parameter = info_fields{i};                                             % get the parameter of each line
    value = info.(info_fields{i});                                          % get the corresponding value of the parameter
    parameter(strfind(parameter,'_')) = ' ';                                % change '_' to ' '
    line=[parameter,' = ',num2str(value)];                                  % create the line of the hdr file
    fprintf(fid,'%s\n',line);                                               % write it to the hdr file
end

fclose(fid);                                                                % clode the header file

end