Matlab Program of Automatically Generating HDR File when Saving Remote Sensing Image.

Posted by Zengfu Hou on March 07, 2021

Welcome to exchange and study!


The following code is based on Matlab 2018b.

%% ==================================================
%% save the results

[FileName, PathName] = uiputfile({'*.img';'*.mat';'*.m';'*.slx';'*.*'},'Save The Result Images As');

% 对文件保持窗口选择是否保存进行判断
if isequal(FileName,0) || isequal(PathName,0)  
    disp('User pressed cancel')
else
    disp(['Save The Result Images As:  ', fullfile(PathName, FileName)])
    savefile_name=strcat(PathName,FileName);
%     disp('Save The Result Images As:');
%     disp(savefile_name);
    % 利用matlab自带multibandwrite函数将矩阵转换成tif文件格式,第一个参数gt是需要写入的矩阵,第二参数为存储路径和命名
    multibandwrite(result_img,char(savefile_name),'bsq','machfmt','ieee-le','precision','double'); % 注意:此处表名,gt为double精度的tif格式

%%============Here is the HDR file generation program=================
% generate *.hdr file
    h1='ENVI';
    h2='description = { Binary Data }';
    h3=['samples = ',num2str(cols)];         % 使用矩阵形式,可以将空格写入TXT文本文件中,使用strcat则无法写入空格
    h4=['lines   = ',num2str(rows)];
    h5=['bands   = ',num2str(bands)];
    h6='header offset = 0';
    h7='file type = ENVI Standard';
    h8='data type = 5';
    h9='interleave = bsq';
    h10='sensor type = Unknown';
    h11='byte order = 0';
    h12='wavelength units = Unknown';
    h={};
    h={h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12};

    if ~isempty(strfind(FileName,'.'))==0;
        fid=fopen(strcat(PathName,strcat(FileName,'.hdr')),'wt');
    else
        hdr_nam=FileName(1:end-4);
        hdr_name=strcat(hdr_nam,'.hdr');
        fid=fopen(strcat(PathName,hdr_name),'wt');
    end
    for i=1:12;
      fprintf(fid,'%s\n',h{i}); 
    end
    fclose(fid);
    % save all results
    save(strcat(PathName,'result_BilaterFilter.mat'))
end
%% ===================================================