4

I am trying to crop the TIF images based on the shape file. After searching the web, I found the following code and manipulated it.

from osgeo import gdal
import os

input_path = '/.../pics' output_path = '/.../clipped_pics/'

bandList = [band for band in os.listdir(input_path) if band[-4:]=='.tif'] shp_clip = '/.../Index.shp'

for band in bandList: print(output_path + band[:-4]+'_c2'+band[-4:]) options = gdal.WarpOptions(cutlineDSName=shp_clip,cropToCutline=True) outBand = gdal.Warp(srcDSOrSrcDSTab=input_path + band, destNameOrDestDS=output_path + band[:-4]+'_c2'+band[-4:], options=options) outBand= None

However, this is the error I get:

TypeError                                 Traceback (most recent call last)
<ipython-input-51-e2d9d6412405> in <module>
      4     outBand = gdal.Warp(srcDSOrSrcDSTab=input_path + band,
      5                         destNameOrDestDS=output_path + band[:-4]+'_c2'+band[-4:],
----> 6                         options=options)
      7     outBand= None

~/opt/anaconda3/lib/python3.7/site-packages/osgeo/gdal.py in Warp(destNameOrDestDS, srcDSOrSrcDSTab, **kwargs) 673 674 if _is_str_or_unicode(destNameOrDestDS): --> 675 return wrapper_GDALWarpDestName(destNameOrDestDS, srcDSTab, opts, callback, callback_data) 676 else: 677 return wrapper_GDALWarpDestDS(destNameOrDestDS, srcDSTab, opts, callback, callback_data)

~/opt/anaconda3/lib/python3.7/site-packages/osgeo/gdal.py in wrapper_GDALWarpDestName(args) 4315 def wrapper_GDALWarpDestName(args): 4316 """wrapper_GDALWarpDestName(char const * dest, int object_list_count, GDALWarpAppOptions warpAppOptions, GDALProgressFunc callback=0, void * callback_data=None) -> Dataset""" -> 4317 return _gdal.wrapper_GDALWarpDestName(*args) 4318 class GDALVectorTranslateOptions(_object): 4319 """Proxy of C++ GDALVectorTranslateOptions class."""

TypeError: object of wrong GDALDatasetShadow

  • The only thing that I can see is that srcDSOrSrcDSTab=input_path + band doesn't have a separator, consider using os.path.join instead of simple concatenation: srcDSOrSrcDSTab=os.path.join(input_path, band) and destNameOrDestDS=os.path.join(output_path, band[:-4]+'_c2'+band[-4:]) which ensures the correct os.sepchar is used to join the path name. You also may want to consider os.path.splitext(band)[1].lower() to break your filename, [-4:] doesn't always work if your raster is .jpeg for example. – Michael Stimson Aug 04 '20 at 06:55
  • 1
    Thank you very much, Michael! It works now. – Rohullah Najibi Aug 05 '20 at 04:28
  • @MichaelStimson, do you happen to have an idea about this question? https://gis.stackexchange.com/questions/370564/problem-with-the-edges-when-clipping-raster – Rohullah Najibi Aug 05 '20 at 04:30
  • 3
    In case it helps anyone, I got the same error because I tried to pass in a pathlib Path object rather than a string. – user55937 Jan 05 '23 at 16:09

0 Answers0