【Matlab】读取".hdr"文件

写在最前

本文主要介绍了 Matlab 中函数 multibandread 的用法以及如何处理hdr文件。
该函数可以用于读取 “.hdr” 文件。

一、函数:multibandread()

% 该函数语法规则为:X = multibandread(filename, size, precision, offset, interleave, byteorder)
% filename: 文件名
% size:图像尺寸和波段数,size = [ 行数 列数 波段数 ]
% precision:读取的图像的数据格式,例如’uint8’,‘uint16’,‘double’等
% offset:偏移
% interleave:存储的图像的数据格式,有 bsq,bil,bip三种格式
% byteorder : 数据存储的字节排列方式,有’ieee-le’(小端),‘ieee-be’(大端)

二、代码

% 标准开头

clear 
close all
clc

% 打开文件

hdr_path_name = '*.hdr';
fid = fopen(hdr_path_name,'r');
info = fread(fid, 'char=>char');
info = info';
fclose(fid);

% 获得函数 multibandread 的参数‘size’
% 首先找到要读取的名称的索引,并获取该名称的数据长度,获取该名称的最后的索引
% 获取列数 info 中为 ‘samples’

start = strfind(info,'samples = '); 
len = length('samples = ');
stop = strfind(info,'lines ');
samples = [];
for i = start+len : stop-1
    samples = [samples, info(i)];
end
samples = str2num(samples);

% 获取行数 info中为‘lines’

start = strfind(info,'lines   = ');
len = length('lines   = ');
stop = strfind(info,'bands');
lines = [];
for i = start+len : stop-1
    lines = [lines, info(i)];
end
lines = str2num(lines);

% 获取波段数 info中为‘bands’

start = strfind(info,'bands   = ');
len = length('bands   = ');
stop = strfind(info,'header offset');
bands = [];
for i = start+len : stop-1
    bands = [bands, info(i)];
end
bands = str2num(bands);

% 获得函数multibandread的参数‘precision’
% 获取data_type

start = strfind(info,'data type = ');
len = length('data type = ');
stop = strfind(info,'interleave');
datatype = [];
for i = start+len : stop-1
    datatype = [datatype, info(i)];
end
datatype = str2num(datatype);

% 获取precision

precision = [];
switch datatype
    case 1
        precision = 'uint8 => uint8';
    case 2
        precision = 'int16 => int16';
    case 12
        precision = 'uint16 => uint16';
    case 3
        precision = 'int32 => int32';
    case 13
        precision = 'uint32 => uint32';
    case 4
        precision = 'float32 => float32';
    case 5
        precision = 'double => double';
    otherwise
        precision = 'invalid type';
end

% 获得函数multibandread的参数‘interleave’
% 获取存储的图像的数据格式

start = strfind(info,'interleave = ');
len = length('interleave = ');
stop = strfind(info,'sensor type');
interleave = [];
for i = start+len : stop-1
    interleave = [interleave, info(i)];
end
interleave = strtrim(interleave);

% 这样就得到multibandread函数的所有参数 multibandread(filename, size, precision, offset, interleave, byteorder)
% 调用上述的函数(截取前1000行 前1000列)

data = multibandread(img_path_name,[lines,samples,bands],precision,0,interleave,'ieee-le',{'Row','Range',[1 1000]},{'Column','Range',[1 1000]});

祝您浏览愉快!

你可能感兴趣的:(【Matlab】读取".hdr"文件)