繁体   English   中英

通过 shapefile 剪切 NetCDF 文件

[英]Cut NetCDF files by shapefile

我有一个大型的全局 .nc 文件数据集,我正在尝试将它们剪辑到一个较小的区域。 我将此区域存储为 .shp 文件。

我曾尝试使用 Qgis 中的 gdal,但需要通过转换每个变量来做到这一点,我必须为所有文件一一选择每个变量和相同的形状,并且每个变量都有 400 个文件,这似乎不是最好的主意。 此外,这会返回分离的 .tiff 文件,而不是我想要的 .nc 文件。

我有这个小脚本,但它没有做我需要的

    import glob
    import subprocess
    import os
    
    ImageList = sorted(glob.glob('*.nc'))
    print('number of images to process: ', len(ImageList))
    
    Shapefile = 'NHAF-250m.shp'
    
    # Create output directory
    OutDir = './Clipped_Rasters/'
    if not os.path.exists(OutDir):
        os.makedirs(OutDir)
    
    for Image in ImageList:
        print('Processing ' + Image)
    
        OutImage = OutDir + Image.replace('.nc', '_BurnedArea_Clipped.tif') # Defines Output Image
    
        # Clip image
        subprocess.call('gdalwarp -q -cutline /Users/path/to/file/NHAF-250-vector/ -tr 0.25 0.25 -of GTiff NETCDF:'+Image+":burned_area "+OutImage, shell=True)
    
    
        print('Done.' + '\n')
    
    print('All images processed.')

先感谢您

我建议使用xarray来处理 netcdf 数据和geopandas + rasterio来处理你的 Shapefile。

import geopandas 
import xarray
import rasterio
import glob

shapefile = 'NHAF-250m.shp'

sf = geopandas.read_file(shapefile)
shape_mask = rasterio.features.geometry_mask(sf.iloc[0],
                                      out_shape=(len(ndvi.y), len(ndvi.x)),
                                      transform=ndvi.geobox.transform,
                                      invert=True)
shape_mask = xarray.DataArray(shape_masj , dims=("y", "x"))

file_list = sorted(glob.glob('*.nc'))

for file in file_list:
    nc_file = xarray.open_dataset(file)
    # Then apply the mask
    masked_netcdf_file = nc_file.where(shape_mask == True, drop=True)
    # store again as netcdf or do what every you want with the masked array
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM