GTiff mask with shapefile in python with gdal, ogr, etc

后端 未结 1 399
抹茶落季
抹茶落季 2021-02-06 10:49

OK, After a bit of fiddling, I\'ve tweaked a script from the site hyperlink in the second comment line. The purpose of the script is to clip/mask a LARGE raster (i.e. that canno

1条回答
  •  抹茶落季
    2021-02-06 11:39

    This functionality is already incorporated into the gdal command line utilities. Given your case, i don't see any reason why you want to do this yourself in Python.

    You can loop over the geomerties with OGR and for each one call gdalwarp with the appropriate parameters.

    import ogr
    import subprocess
    
    inraster = 'NE1_HR_LC_SR_W_DR\NE1_HR_LC_SR_W_DR.tif'
    inshape = '110m_cultural\ne_110m_admin_0_countries_lakes.shp'
    
    ds = ogr.Open(inshape)
    lyr = ds.GetLayer(0)
    
    lyr.ResetReading()
    ft = lyr.GetNextFeature()
    
    while ft:
    
        country_name = ft.GetFieldAsString('admin')
    
        outraster = inraster.replace('.tif', '_%s.tif' % country_name.replace(' ', '_'))    
        subprocess.call(['gdalwarp', inraster, outraster, '-cutline', inshape, 
                         '-crop_to_cutline', '-cwhere', "'admin'='%s'" % country_name])
    
        ft = lyr.GetNextFeature()
    
    ds = None
    

    I have used some example data from Natural Earth in the example above, for Brazil the cutout looks like:

    enter image description here

    If you only want to crop the image to the area of the polygon and dont mask anything outside you can transform the Shapefile so it contains the envelope of the polygons. Or simply loose the shapefile and call gdal_translate with -projwin to specify the area of interest.

    0 讨论(0)
提交回复
热议问题