from genericpath import exists
from osgeo import gdal
import os
import argparse
def clip(inputpath:str,inputRaster:str,mask,outPath):
index=inputRaster.rindex('.')
outputRaster=inputRaster[0:index]+'_clip'+inputRaster[index:]
gdal.Warp(os.path.join(outPath,outputRaster),
os.path.join(inputpath,inputRaster),
cutlineDSName=mask,
format='GTiff',
cropToCutline=True,
copyMetadata=True,
dstNodata=np.nan,
options=['COMPRESS=LZW'])
print('{} has been created!'.format(os.path.join(outDir,outputRaster)))
parser=argparse.ArgumentParser('批量裁剪栅格影像')
parser.add_argument('inputDir',type=str,help='the path to dir where the raster to clip is stored in')
parser.add_argument('mask',type=str,help='the path of mask file')
parser.add_argument('outDir',type=str,help='the path to store the results',default=None)
args=parser.parse_args()
inputDir=args.inputDir
if not(os.path.exists(inputDir)):
print('{} doesn\'t exists!'.format(inputDir))
exit()
outDir=args.outDir
if not(os.path.exists(outDir)):
os.makedirs(outDir)
mask=args.mask
if not(os.path.exists(mask)):
print('{} doesn\'t exists!'.format(mask))
inputRasters=os.listdir(inputDir)
for inputRaster in inputRasters:
clip(inputDir,inputRaster,mask,outDir)
print('finisned!')