MATLAB读raw,dat文件代码

1.读取raw文件,没有帧头:

function [image,k] = readraw1(M, N)
[filename, pathname] = uigetfile('*.raw', '读入图像');
f1 = fopen([pathname, filename], 'r')
data = fread(f1, 'uint16');
fclose(f1);
len = length(data);
k = len/(M*N);
image = reshape(data, M, N, k);
end

2.读取raw文件,有帧头(自己根据帧头信息改动哇,数据的帧头信息不一样读取方法不一样)

function  [data,Len1] = readraw(M,N)

%% 读入文件
[filename, pathname] = uigetfile('*.raw','图像文件'); 
D = dir(strcat(pathname,filename));
length = D.bytes;
Len1 = length/(M*N*2+31);

data = zeros(M,N,Len1);

f1=fopen([pathname filename],'r');
for k = 1:Len1
frewind(f1);%指针指向数据最前端
f2=fseek(f1,27*k+512*576*2*(k-1)+4*(k-1),0);
data(:,:,k)=fread(f1,[M,N],'uint16','b');

end
fclose(f1);

3.dat数据文件,有帧头信息,标识符是FDFD。。。。。。。。。。。。。。AA,先读一帧找到帧头在继续读下面的图像。257*328,M=256,N=320

function [image] = readraw1(M, N,num)
[filename, pathname] = uigetfile('*.*', '读入图像');
f1 = fopen([pathname, filename], 'r');
% data = fread(f1,168592, 'uint16','b');%b是高地位转换,uint16读
data = fread(f1,168592+2, 'uchar');%8位字符型,肯定包含一个开头,只是为了找到帧头
fclose(f1);
len = length(data);
k = floor(len/((M+1)*(N+8)*2));
a = [];
for i =1:len-320
   if data(i)==253&&data(i+1)==253&&data(i+9)==170
       i = floor(i/2);
       a = [a;i];
   end
end

f1 = fopen([pathname, filename], 'r');
data = fread(f1,168592*(num+1), 'uint16');%8位字符型
fclose(f1);
locate = a(1);%找到第一个头的位置
data_final = data(locate+1:locate+328*257*num);

image = reshape(data_final,  N+8,M+1,num);

end

4.读取文件夹中的所有nii图像

%files1 = gunzip('*.nii.gz');
%files2 = gunzip('*.nii.gz');
%nii_ADC = load_nii('*.nii');
%nii_DWI = load_nii('*.nii');

%[filename, pathname] = uigetfile('*.nii', '读入图像');
pathname = uigetdir(); 
filename =[pathname,'\*.nii'];
namelist = dir(filename);%获取该文件夹中所有nii格式的图像
img_num = length(namelist);%获取图像总数量
if img_num > 0 %有满足条件的图像
        for j = 1:img_num %逐一读取图像
            image_name = namelist(j).name;% 图像名
            image_structure(j) =  load_nii(image_name);
            image_data = image_structure(j).img;
            data_size = size(image_data)
            figure(j),
            for i = 1:data_size(3)
                imshow(image_data(:,:,i),[]);% 显示正在处理的图像名
                set(gcf,'outerposition',get(0,'screensize'));%最大化
                pause(1)
            end
            
            %图像处理过程 省略
        end
end

 

你可能感兴趣的:(MATLAB编程,读文件MATLAB)