我有几个栅格,其中像素信息是高程数据。但是,图像中存在许多无数据值(零),超出了我想要的数据范围,因此文件大小不必要地大。我尝试使用gdal和numpy的混合裁剪图像,但是我注意到图像中有一个小的亚像素大小的偏移。这是舍入错误,可以采取任何措施解决此问题吗?
它在某些地方不是很好的Python语言,但是似乎可以正常工作,除了很小的移位
我也愿意使用python / numpy / gdal ...的任何其他方法...
我的代码是:
from osgeo import gdal
import numpy as np
import os
import subprocess
np.set_printoptions(threshold=np.nan)
inDir = '/path/to/files'
outDir = '/path/for/outfiles'
files = [file for file in os.listdir(inDir) if file.endswith('.tif')]
for file in files:
outfile= os.path.join(outDir, file)
if os.path.isfile(outfile):
print('File exists')
pass
else:
try:
print(file)
# open raster and read in the data
dataset = gdal.Open(file)
band = dataset.GetRasterBand(1)
Cols = dataset.RasterXSize
Rows = dataset.RasterYSize
print('Reading Radar data...')
data = band.ReadAsArray(0, 0, Cols, Rows).astype(np.float)
# Read in the projection onfo
ulx, xres, xskew, uly, yskew, yres = dataset.GetGeoTransform()
# define the corner co-ords
ulx = ulx
uly = uly
lrx = ulx + (dataset.RasterXSize * xres)
lry = uly + (dataset.RasterYSize * yres)
# Make two arrays with the co-ords for each pixel
XP = np.arange(ulx, lrx, xres, dtype=np.float64)
YP = np.arange(uly, lry, yres, dtype=np.float64)
# Make an array the same shape as data populated with the X dimensions
print('Building X dimensions...')
Xarr = np.zeros_like(data)
Xarr[...] = XP
# Make an array the same shape as data populated with the Y dimensions
print('Building Y dimensions...')
Yarr = np.zeros_like(data)
Yarr = Yarr.transpose()
Yarr[...] = YP
Yarr = Yarr.transpose()
# Mask out the X and Y co-ords arrays based on presence of valid data
print('Subsetting data...')
SubXarr = Xarr[data > 0]
SubYarr = Yarr[data > 0]
SubData = data[data > 0]
#Get the bounding co-ords based on presence of valid data
# note yres is -ve
print('Finding corner coords...')
Xmin = np.amin(SubXarr)
Xmax = np.amax(SubXarr) + abs(xres)
Ymin = np.amin(SubYarr) - abs(yres)
Ymax = np.amax(SubYarr)
print(Xmin, Ymin)
print(Xmax, Ymax)
# Subset the input image based on the bounding co-ords
outfile = os.path.join(outDir, file)
print('Cropping Data to ' + str(outfile.split('/')[-1]))
subprocess.call('gdalwarp -of GTiff -r cubic -tr ' + str(xres) + ' ' + str(yres) + ' -te ' + str(Xmin) + ' ' + str(Ymin) + ' ' + str(Xmax) + ' ' + str(Ymax) + ' -tr ' + str(xres) + ' ' + str(yres) + ' ' + str(file) + ' ' + str(outfile),shell=True)
except Exception as e:
print(e)
print('Could not process: ', str(outfile.split('/')[-1]))