MATLAB 批量读取NC文件并转为TIF文件

因为课题处理30年的降雨和蒸发的遥感资料(.NC格式),而想要在Arcgis中处理要求的是raster格式的,所以需要批量转化为tif文件,所以在此分享自己改编之后的代码,可以简洁明了的实现这个过程:

我所参考和借鉴的文章的链接如下:
https://blog.csdn.net/liyanzhong/article/details/51884735 《 MATLAB读取.nc文件》
http://bbs.06climate.com/forum.php?mod=viewthread&tid=39013&page=1 《matlab批量处理nc文件》
bbs.06climate.com/forum.php?mod=viewthread&tid=59998 《Matlab读取气象驱动数据.nc格式的数据》 感谢他们的分享

版本:MATLAB_2018b

clc;
clear;

%% 批读取NC文件的准备工作
datadir = 'G:\Global_P_ET\MSWEP_V2.2\'; %指定批量数据所在的文件夹
filelist = dir([datadir,'*.nc']); %指定批量数据的类型
% a = filelist(1).name;  %查看要读取的文件的编号
% b = filelist(2).name;
k=length(filelist);

for i = 1:k  %依次读取并处理
    
    %% 批量读取NC文件
    ncFilePath = ['G:\Global_P_ET\MSWEP_V2.2\',filelist(i).name]; %设定NC路径
    num = filelist(i).name(1:6); %读取数据编号,以便于保存时以此编号储存tif
      
    %% 读取变量值
    lon=ncread(ncFilePath,'lon'); %读取经度
    lat=ncread(ncFilePath,'lat'); %读取维度
    time=ncread(ncFilePath,'time');%读取时间序列
    pre=ncread(ncFilePath,'precipitation');%获取降雨变量数据
    sum_pre=sum(pre,3); %此处我是为了求月总降水,所以他人可以不管
   
    %% 展示数据
    % pcolor(lat,lon,sum_pre);
    % shading flat;  %移除网格线,否则图上一片黑什么都没有
    % [x,y]=meshgrid(lon,lat);%根据经纬度信息产生格网,3600列(经度),1800列(纬度)
    % phandle=pcolor(x,y,sum_pre');%显示一个矩阵,其中x,y,sum_pre的行列数必须一致
    % shading flat;
    % colorbar
    % imwrite(sum_pre','...................................','tif')
    
    %% 存为tif格式
    data=flipud(sum_pre');  %很重要,这是镜像反转,否则最后的图像的南北朝向是错的
    R = georasterref('RasterSize', size(data),'Latlim', [double(min(lat)) double(max(lat))], 'Lonlim', [double(min(lon)) double(max(lon))]); 
    geotiffwrite(['G:\Global_P_ET\P\',num,'.tif'],data,R);
    disp([num,'done'])
    
end
disp('finish!')

如果仔细看了上述代码,应该会发现在最后一块中用了flipud函数,这一步镜像反转的作用还可通过下例而知:

clc;
clear;
datadir = 'G:\Global_P_ET\ET\AVHRR_Zhang\';%specify the location of folder of batch data
filelist = dir([datadir,'*.nc']);      %specify the type of batch data
% a = filelist(1).name;                %check the number of document being read
% b = filelist(2).name;
k = length(filelist);

for i = 1:k
    
    %% batch process to read the .NC ducuments
    ncFilePath = ['G:\Global_P_ET\ET\AVHRR_Zhang\',filelist(i).name];
    num = filelist(i).name(19:22);       %record the serial number
      
    %% read the value of variables 
    lon = ncread(ncFilePath,'LON')';    %read value of longitude
    lat = ncread(ncFilePath,'LAT')';    %read value of latitude
    lon = lon(1,:);
    lat = lat(:,1);
    evapotranspiration = ncread(ncFilePath,'monthly_ET'); %read variable's value of precipitation
    
    for mon=1:12
        
        % display data
%         pcolor(lat,lon,data);
%         shading flat;                    %Remove the grid lines from the diagram
%         lon = lon(1,:);
%         lat = lat(:,1);
%         [x,y] = meshgrid(lon,lat);       %generate grids based on lat and lon infomation
%         phandle = pcolor(x,y,data');     %Displays a matrix where x,y,sum pre must have the same number of raws and columns
%         shading flat;
%         colorbar
%         % imwrite(evap1','E:\?????NC??-MATLAB??\aa.tif','tif')

        %% Save as a geographic grid tif format for arcgis to read
        data = flipud(permute(evapotranspiration(mon,:,:),[3 2 1]));   %since we did dimensionality reduction, the flipud function here is important to do vertical reversal 
        R = georasterref('RasterSize', size(data),'Latlim', [double(min(lat)) double(max(lat))], 'Lonlim', [double(min(lon)) double(max(lon))]); 
        if mon<10                          % insert '0' so that can be in format of '0*'
            geotiffwrite(['G:\Global_P_ET\ET_1\', num ,'0',num2str(mon) ,'.tif'],data,R);
            disp([num,'0',num2str(mon),'done'])
        else
            geotiffwrite(['G:\Global_P_ET\ET_1\', num ,num2str(mon) ,'.tif'],data,R);
            disp([num,num2str(mon),'done']) 
        end        
    end
end
disp('finish!')

二者代码的区别及要点如下:

1.在读入文件时可以预先用Panoply读一下NC文件看看各个变量的名字、大小写以及维度,比如第二个代码中变成了二维的’LON’、‘LAT’和’monthly_ET’。如果没有Panoply也可以用以下代码:

%% 显示结构
% ncdisp(ncFilePath);%显示nc文件的所有结构,以便大概了解里面的内容
% ncdisp(ncFilePath,'evap');%显示指定变量的内容,注意一定要是变量variables才可以
% ncdisp(ncFilePath,'/','min');%简单显示结构以及定义
% ncdisp(ncFilePath,'/','full');%全部显示所有结构和定义信息


%% 读取变量值
% ncid = netcdf.open(ncFilePath,'NOWRITE'); %打开nc文件返回索引ID
% [ndims,nvars,ngglobalatts,unlimdimid] = netcdf.inq(ncid);%获取维数,变量数,全局属性数量,
% [varname,xtype,dimids,natts] = netcdf.inqVar(ncid,0); %根据变量索引号获取变量的名称
--------------------- 
作者:忠言睿长 
来源:CSDN 
原文:https://blog.csdn.net/liyanzhong/article/details/51884735 

2.注意数据的维度以及在降维时的旋转问题,这也是为什么要用flipud函数进行矩阵上下翻转的原因,蒸发数据还好,如果是错的看图一下就能分辨出来,降雨数据就要小心再小心!!!

3.在输出命名时,进行判定加 ‘0’ ,这样就能使最后的图像按着1-12月的顺序排下来,包括之后的读取栅格平均值都很有必要!

希望能帮到你!

猜你喜欢

转载自blog.csdn.net/qq_38882446/article/details/88656478
今日推荐