nc文件转tif代码

该代码段使用Matlab读取NetCDF文件中的经度、纬度、时间及覆盖度数据,通过imagesc和pcolor展示数据,然后将数据转换为tif格式,利用georasterref和geotiffwrite进行地理栅格化和保存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

clc
clear 
ncFilePath = ['D:\homework\nc\c_gls_FCOVER-RT0_202006300000_GLOBE_PROBAV_V2.0.1.nc']; %设定NC路径
ncdisp(ncFilePath); %查看nc文件变量
 %% 读取变量值
    %根据ncdisp函数读取到的nc文件变量相应替换
    lon=ncread(ncFilePath,'lon');     %读取经度信息(范围、精度)
    lat=ncread(ncFilePath,'lat');      %读取维度信息
    time=ncread(ncFilePath,'time');         %读取时间序列
    DUS=ncread(ncFilePath,'FCOVER');   %获取覆盖度数据 
 %% 展示数据内部结构等信息
     %figure(i);
     imagesc(lat,lon,DUS);
     shading flat;                        %移除网格线,否则图上一片黑什么都没有
     [x,y]=meshgrid(lon,lat);             %根据经纬度信息产生格网,3600列(经度),1800列(纬度)
     %phandle=pcolor(x,y,DUS');        %显示一个矩阵,其中x,y,DUS的行列数必须一致
     shading flat;
     colorbar
%% 存为tif格式
    data=flipud(rot90(DUS,1));   %镜像反转,不反转的话最后的图像的南北朝向是错的
                                 %逆时针旋转90°*n,此时n为1,可自行设置调整
    data1=flipud(data);  %图像上下翻转
    %georasterref 绘制地理栅格数据(raster data);double双精度浮点数,保留16位有效数字
    R = georasterref('RasterSize', size(data1),'Latlim', [double(min(lat)) double(max(lat))], 'Lonlim', [double(min(lon)) double(max(lon))]);
    %geotiffwrite geotiff栅格影像保存
    geotiffwrite(['D:\homework\nc\fcover.tif'],data1,R);
disp('Done!')

### 将NetCDF文件逐日换为GeoTIFF 为了实现将NetCDF(nc文件逐日批量换为GeoTIFF(tif)格式的任务,可以采用Python中的`netCDF4`库读取NetCDF文件,并使用`rasterio`库创建并保存GeoTIFF文件。以下是详细的代码示例: #### 安装所需依赖包 首先确保安装了必要的Python库: ```bash pip install netcdf4 rasterio numpy pandas ``` #### Python脚本实现批处理换 下面是一个完整的Python脚本,用于遍历指定目录下的所有.nc文件,并将其按日期逐一换成对应的.tif文件。 ```python import os from datetime import datetime, timedelta import netCDF4 as nc import numpy as np import rasterio from rasterio.transform import from_origin def convert_nc_to_tif(nc_file_path, output_dir): """ Convert a single NetCDF file to GeoTIFF. Args: nc_file_path (str): Path of the input .nc file. output_dir (str): Directory where generated tifs will be saved. Returns: None """ # 打开NetCDF文件 dataset = nc.Dataset(nc_file_path) variable_name = list(dataset.variables.keys())[3] # 假设第四个变量是要提取的数据[^1] time_var = dataset['time'] dtime = nc.num2date(time_var[:], time_var.units) lon = dataset['longitude'][:] lat = dataset['latitude'][:] for i in range(len(dtime)): date_str = dtime[i].strftime('%Y%m%d') out_filename = f"{output_dir}/{os.path.basename(nc_file_path).split('.')[0]}_{date_str}.tif" data = dataset[variable_name][i, :, :] transform = from_origin(lon.min(), lat.max(), abs(lon[1]-lon[0]), abs(lat[1]-lat[0])) with rasterio.open( out_filename, 'w', driver='GTiff', height=data.shape[0], width=data.shape[1], count=1, dtype=str(data.dtype), crs='+proj=latlong', # CRS can vary based on your needs transform=transform, ) as dst: dst.write(data.astype(rasterio.float32), indexes=1) def batch_convert(directory_with_nc_files, target_directory): """ Batch process all .nc files within given directory. Args: directory_with_nc_files (str): Source folder containing NC files. target_directory (str): Destination folder for TIF outputs. Returns: None """ if not os.path.exists(target_directory): os.makedirs(target_directory) for filename in os.listdir(directory_with_nc_files): if filename.endswith(".nc"): fullpath = os.path.join(directory_with_nc_files, filename) try: convert_nc_to_tif(fullpath, target_directory) print(f'Successfully converted {filename}') except Exception as e: print(f'Failed converting {filename}: ', str(e)) # Example usage source_folder = '/path/to/your/netcdfs' destination_folder = '/desired/output/path' batch_convert(source_folder, destination_folder) ``` 此脚本会自动查找源文件夹内的所有`.nc`文件,并依次调用函数`convert_nc_to_tif()`来完成单个文件到多个`tif`切片的换工作。注意调整路径参数以匹配实际环境需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dropout_z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值