nc数据批量转为tiff数据的python代码
时间: 2023-09-22 15:06:57 浏览: 102
以下是Python代码:
```python
import os
import gdal
import numpy as np
def nc_to_tiff(nc_path, tiff_path):
# 打开netCDF文件
nc_dataset = gdal.Open(nc_path)
# 读取数据的维度和大小
xsize = nc_dataset.RasterXSize
ysize = nc_dataset.RasterYSize
bands = nc_dataset.RasterCount
# 获取变量名
var_name = nc_dataset.GetSubDatasets()[0][0].split(":")[-1]
# 创建输出文件
driver = gdal.GetDriverByName("GTiff")
out_dataset = driver.Create(tiff_path, xsize, ysize, bands, gdal.GDT_Float32)
# 将每个变量写入TIFF文件
for band in range(bands):
band_data = nc_dataset.GetRasterBand(band+1).ReadAsArray()
out_dataset.GetRasterBand(band+1).WriteArray(band_data)
out_dataset.GetRasterBand(band+1).SetDescription(var_name)
out_dataset.SetProjection(nc_dataset.GetProjection())
out_dataset.SetGeoTransform(nc_dataset.GetGeoTransform())
out_dataset = None
nc_dataset = None
```
调用方法:
```python
nc_path = "path/to/nc/file.nc"
tiff_path = "path/to/tiff/file.tif"
nc_to_tiff(nc_path, tiff_path)
```
注:此代码仅适用于读取单个变量的单层数据,如需批量处理多个变量或多层数据,需要稍作修改。
阅读全文