在 Python 中读取 .grd 文件

Reading .grd file in Python

ESRI grid format中的一些文件(后缀为.grd)是一个地理空间数据集,具有左下X角,左下Y角和值。

文件看起来像这样(使用 vim 读取它):

   1 ncols 2880
   2 nrows 1440
   3 xllcorner -180.0
   4 yllcorner  -90.0
   5 cellsize 0.125
   6 nodata_value -999
   7 version 2.0

   8  -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 ...

目前,我使用手动预处理方法处理这些文件。

  1. 删除前 7 行
  2. 将 .grd 文件保存到 .txt 文件中。
  3. 使用 numpy 将 .txt 文件读取到表示空间属性的 numpy 数组中
  4. 结合前7行,生成属性数组对应的Lon和Lat数组(对于我的cas (1440 x 2880))

现在想实现直接读取文件:

我的尝试

 ## Read the first seven lines using LineCache
 ncols = linecache.getline("grd file", 1)
 ......
 ## Read the array using np.loadtxt()
 myArray  = np.loadtxt("grd file", skiprows=7) 

你可以为它写一个函数。这是一个示例(假设您的行号来自 vim,实际上并不存在于文件中):

import numpy as np

def read_grd(filename):
    with open(filename) as infile:
        ncols = int(infile.readline().split()[1])
        nrows = int(infile.readline().split()[1])
        xllcorner = float(infile.readline().split()[1])
        yllcorner = float(infile.readline().split()[1])
        cellsize = float(infile.readline().split()[1])
        nodata_value = int(infile.readline().split()[1])
        version = float(infile.readline().split()[1])
    longitude = xllcorner + cellsize * np.arange(ncols)
    latitude = xllcorner + cellsize * np.arange(nrows)
    value = np.loadtxt(filename, skiprows=7)

    return longitude, latitude, value