Python:网格点X,Y和Z,以便提取统计属性

时间:2012-09-27 12:21:48

标签: python numpy geospatial raster gdal

很抱歉这个简单的问题,但我是Python的新手,我需要同样的帮助。

我的数据采用点格式:X,Y,Z。其中X和Y是坐标,z是值。

我的问题是:用0.5米乘0.5米(或1乘1米)创建一个光栅(用TIF或ASCII格式),其中每个像素的值是Z的平均值。如果我没有点在pixel-i值必须为NAN。

我很高兴能帮助我学习和实施一些代码,

在预先感谢您的帮助,我真的需要。

我尝试学习并编写代码:

from osgeo import gdal, osr, ogr
import math, numpy
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as ml
import matplotlib.delaunay

tiff = 'test.tif'

gridSize = 0.5
# my area boundary
xmax, xmin = 640000.06, 636999.83
ymax, ymin = 6070000.3, 6066999.86

# number of row and columns
nx = int(math.ceil(abs(xmax - xmin)/gridSize))
ny = int(math.ceil(abs(ymax - ymin)/gridSize))

# Plot the points
plt.scatter(x,y,c=z)
plt.axis([xmin, xmax, ymin, ymax])
plt.colorbar()
plt.show()

# Generate a regular grid.
xi = np.linspace(xmin, xmax, nx)
yi = np.linspace(ymin, ymax, ny)
xi, yi = np.meshgrid(xi, yi)

从这一点来看,我有一个问题,就是要了解x,y,z的索引是如何指出的,以便知道它们在哪里掉落。我的第一个想法是给网格网格索引并标记点。之后,我可以对像素内的点进行平均。像素为空(没有现在的点)是NAN。

但我不知道这是处理我的数据的正确方法。

之后我编写了以下代码,通过GDAL

以TIFF格式保存
target_ds = gdal.GetDriverByName('GTiff').Create(tiff, nx,ny, 1, gdal.GDT_Byte) #gdal.GDT_Int32
target_ds.SetGeoTransform((xmin, gridSize, 0,ymax, 0, -gridSize,))

if EPSG == None:
    proj = osr.SpatialReference()
    proj.ImportFromEPSG(EPSG)
    # Make the target raster have the same projection as the source
    target_ds.SetProjection(proj.ExportToWkt())
else:
    # Source has no projection (needs GDAL >= 1.7.0 to work)
    target_ds.SetProjection('LOCAL_CS["arbitrary"]')

target_ds.GetRasterBand(1).WriteArray(numpy.zeros((ny,nx)))
target_ds = None

非常感谢所有帮助

1 个答案:

答案 0 :(得分:5)

一种方法:

  • 定义您的网格spacing(浮点数),即同一维度中两个像素/体素中点之间的距离
  • 计算出您需要的网格大小,即xy维度,N_xN_y中网格点的数量。
  • 创建该大小的两个numpy数组,所有值均为零,例如使用np.zeros([N_x, N_y])
  • 遍历你的(x,y,v)点和
    • 将每个(x,y)对投影到其对应的像素中,通过两个(整数)索引识别:x_i, y_i = tuple([int(c//spacing) for c in (x, y)])
    • 在地点(x_i, y_i)(保持“计数”)
    • 的位置添加1
    • 将值v添加到位置(x_i, y_i)的另一个数组中(保存值的总和)
  • 填充两个数组后,将sum-of-values-array除以count-array。 0 / 0.0将自动分配给NaN,而c / 0.0将分配为Inf