我正在尝试使用python gdal库创建栅格,现在已经到了输出数据的地步,但是输出数据在原点的x轴上翻转了。我知道我一定在忽略某些东西,但是我无法弄清楚哪里出了问题。有任何想法吗?
创建栅格时,我设置了左上角的x / y值,该数组似乎从左上角开始索引,然后继续向下到右下角。在下面的代码中,我用行的值填充数组。
打印数组时,它看起来像这样:
[[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
1. 1. 1. 1. 1. 1.]
[ 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.
2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.
2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.
2. 2. 2. 2. 2. 2.]
[ 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.
3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.
3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.
3. 3. 3. 3. 3. 3.]
[ 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4.
4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4.
4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4.
4. 4. 4. 4. 4. 4.]
...
并且该数据成功写入光栅带。但是,在MapWindow GIS中查看时,数据的方向与原始设置的左上原点相反,并显示为左下值。
换句话说,数据在原点的x轴上翻转。
import gdal
import osr
import numpy
OUTPUT_FORMAT = "GTiff"
def create_raster(filename="test.tif"):
driver = gdal.GetDriverByName(OUTPUT_FORMAT)
band_type = gdal.GDT_Byte
number_of_bands = 1
x_rotation = 0 # not supported
y_rotation = 0 # not supported
cell_width_meters = 50
cell_height_meters = 50
(min_lon, min_lat, max_lon, max_lat) = _get_point_bounds() # retrieve bounds for point data
srs = osr.SpatialReference()
srs.SetWellKnownGeogCS("WGS84") # Set geographic coordinate system to handle lat/lon
srs.SetUTM( 54, True) # Set projected coordinate system to handle meters
# create transforms for point conversion
wgs84_coordinate_system = srs.CloneGeogCS() # clone only the geographic coordinate system
wgs84_to_utm_transform = osr.CoordinateTransformation(wgs84_coordinate_system, srs)
# convert to UTM
top_left_x, top_left_y, z = wgs84_to_utm_transform.TransformPoint(min_lon, max_lat, 0)
lower_right_x, lower_right_y, z = wgs84_to_utm_transform.TransformPoint(max_lon, min_lat, 0)
cols, rows = _get_raster_size(top_left_x, lower_right_y, lower_right_x, top_left_y, cell_width_meters, cell_height_meters)
dataset = driver.Create(filename, cols, rows, number_of_bands, band_type) #
# GeoTransform parameters
# --> need to know the area that will be covered to define the geo tranform
# top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
geo_transform = [ top_left_x, cell_width_meters, x_rotation, top_left_y, y_rotation, cell_height_meters ]
dataset.SetGeoTransform(geo_transform)
dataset.SetProjection(srs.ExportToWkt())
dataset_band = dataset.GetRasterBand(1)
data = dataset_band.ReadAsArray(0, 0, cols, rows).astype(numpy.float32) # returns empty array
for row in xrange(rows):
for col in xrange(cols):
data[row][ col] = row + 1
dataset_band.WriteArray(data, 0, 0)
dataset_band.SetNoDataValue(0.0)
dataset_band.FlushCache()
dataset = None # Close file
我还注意到,当我为给定的经度/经度计算像素位置时,y值会导致负索引,考虑到数组是从左上角到右下角,这似乎是正确的。
inverse_geo_transform = gdal.InvGeoTransform(self.geo_transform)[1] # for mapping lat/lon to pixel
pixel_x, pixel_y = gdal.ApplyGeoTransform(self.inverse_geo_transform, utm_x, utm_y)