I want to batch extract raster(.tif) covered by a vector file(.shp). how to operate in python? Could you give an example?

closed as off-topic by Vince, John Powell, PolyGeo Dec 15 '16 at 4:04

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions seeking help to debug/write/improve code must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Providing a clear problem statement and evidence of a code attempt will help others to help you. See: How to create a Minimal, Complete, and Verifiable example." – John Powell, PolyGeo
If this question can be reworded to fit the rules in the help center, please edit the question.


If you are using Linux/Mac, you could try the following. It makes use of glob (filename matching) to search for '.tif' files in the current directory. gdalwarp is used to subset the rasters.

import glob
import subprocess
import os

ImageList = sorted(glob.glob('*.tif'))

Shapefile = 'Name_of_Vector.shp'

TargetRes = '10 10' # Defines the target resolution

# Create output directory
OutDir = './Clipped_Rasters/'
if not os.path.exists(OutDir):

for Image in ImageList:
    print('Processing ' + Image)

    OutImage = OutDir + Image.replace('.tif', '_Clipped.tif') # Defines Output Image

    # Clip image
    subprocess.call('gdalwarp -of GTiff -co "COMPRESS=DEFLATE" -tr '+TargetRes+ ' -cutline ' +Shapefile+ ' -crop_to_cutline ' +Image+ ' ' +OutImage, shell=True)

    # Build image overviews
    subprocess.call('gdaladdo --config COMPRESS_OVERVIEW DEFLATE ' +OutImage+ ' 2 4 8 16 32 64', shell=True)

    print('Done.' + '\n')

print('All images processed.')

There are other useful options for gdalwarp. For example, nearest neighbour resampling is used by default, but you can change this using the '-r' option. You can also specify the nodata value using the '-dstnodata' command.

  • Are there any tutorial for operate gdalwarp? Such as type the code format, grammar. I really confused! – chaobin zhang Dec 30 '16 at 8:28
  • Need it to install win exe GDAL-2.1.2.win32-py3.4.msi? The gdal I use is installed by conda. How to call the gdalwarp – chaobin zhang Mar 1 '17 at 12:29
  • I'm sorry. I don't use Windows, so I can't help with your installation problems. – Osian Mar 21 '17 at 8:02
  • The above script will work on unix systems where gdalwarp can be called (within Bash shell) through the subprocess module. This should also work in a conda environment as long as you have set the correct environment paths to Python. – Osian Mar 21 '17 at 8:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.