python nc转为栅格数据
时间: 2024-12-31 08:29:54 浏览: 15
### 将NetCDF文件转换为栅格数据
对于将NetCDF文件转换成栅格TIFF格式的任务,可以利用`rasterio`库配合`netCDF4`来读取并写入地理空间数据。下面提供了一种较为稳健的方法,能够有效避免生成图像时可能出现的上下颠倒问题以及确保坐标系统的准确性[^1]。
#### 安装必要的Python包
如果尚未安装所需的软件包,则可以通过pip命令完成安装:
```bash
pip install netcdf4 rasterio numpy
```
#### Python脚本实现NC至TIFF转换
接下来展示一段用于执行此操作的具体代码片段。这段程序会遍历指定路径下的所有`.nc`文件,并将其内部变量逐个导出成为独立的GeoTIFF文件。特别注意,在创建输出文件之前设置好正确的仿射变换参数和投影信息是非常重要的,这有助于保持原始地理位置不变形。
```python
import os
from netCDF4 import Dataset
import rasterio
from rasterio.transform import from_origin
import numpy as np
def nc_to_tiff(nc_file, output_folder):
"""
Convert NetCDF file to multiple GeoTIFF files based on variables.
:param str nc_file: Path of the input .nc file.
:param str output_folder: Directory where resulting TIFFs will be saved.
"""
# Open dataset using netCDF4 library
with Dataset(nc_file) as src_ds:
lons = src_ds.variables['lon'][:]
lats = src_ds.variables['lat'][:]
# Determine transform and CRS information before writing any data
west_bound = min(lons)
north_bound = max(lats)
res_x = abs(np.mean((lons[1:] - lons[:-1])))
res_y = abs(np.mean((lats[1:] - lats[:-1])))
dst_transform = from_origin(west_bound, north_bound, res_x, res_y).to_gdal()
for var_name in src_ds.variables.keys():
if 'time' not in var_name.lower() and 'bounds' not in var_name.lower(): # Skip time-related or bounds variables
variable_data = src_ds[var_name][:].squeeze()
# Handle potential issues related to longitude wrapping around [-180, 180]
lon_idx = (lons >= 180)
if np.any(lon_idx):
shifted_lons = ((lons + 180) % 360) - 180
sorted_indices = np.argsort(shifted_lons)
adjusted_lon = shifted_lons[sorted_indices]
adjusted_var_data = variable_data[:, sorted_indices]
lons = adjusted_lon
variable_data = adjusted_var_data
tif_filename = f"{output_folder}/{var_name}.tif"
with rasterio.open(
tif_filename,
'w',
driver='GTiff',
height=variable_data.shape[-2],
width=variable_data.shape[-1],
count=1,
dtype=str(variable_data.dtype),
crs='+proj=latlong', # Assuming WGS84 geographic coordinate system
transform=rasterio.Affine.from_gdal(*dst_transform)) as dst:
dst.write(variable_data.astype(rasterio.float32), indexes=1)
# Example usage
input_nc_path = "path/to/your/input.nc" # Replace this path accordingly
output_dir = "./tiffs/" # Output directory; ensure it exists prior running script
os.makedirs(output_dir, exist_ok=True)
nc_to_tiff(input_nc_path, output_dir)
```
上述过程不仅解决了经纬度范围跨越国际日期变更线的问题,还通过调整数组索引来修正可能存在的经度顺序错乱情况,从而使得最终得到的地图更加精确地反映实际地理分布特征。
阅读全文