1

I am working on a code to clip a raster with another raster. I have a forestcover.tiff image and I want to clip it by using other image clip.tiff which extend lies within it. I don't want to use arcpy module because it requires ArcGIS installed. My code should work for all users.

nmtoken
  • 13,355
  • 5
  • 38
  • 87

1 Answers1

1

You can use the subprocess module with the GDAL command line utilities to solve this.

import subprocess

#input files
forestcover = "/data/forestcover.tif"
clip = "/data/clip.tif"

#output files
cutline = "/data/cutline.shp"
result = "/data/result.tif"

#create the cutline polygon
cutline_cmd = ["gdaltindex", cutline, clip]
subprocess.check_call(cutline_cmd)

#crop forestcover to cutline
#Note: leave out the -crop_to_cutline option to clip by a regular bounding box
warp_cmd = ["gdalwarp", "-of", "GTiff", "-cutline", cutline, "-crop_to_cutline", forestcover, result]
subprocess.check_call(warp_cmd)
Kersten
  • 9,899
  • 3
  • 37
  • 59