Документация по gdal grid

Материал из GIS-Lab
Перейти к навигации Перейти к поиску

gdal_grid

создание регулярных растровых матриц из рассеянных векторных данных.

SYNOPSIS

gdal_grid [-ot {Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/
          CInt16/CInt32/CFloat32/CFloat64}]
	  [-of format] [-co "NAME=VALUE"]
	  [-zfield field_name]
	  [-a_srs srs_def] [-spat xmin ymin xmax ymax]
          [-clipsrc <xmin ymin xmax ymax>|WKT|datasource|spat_extent]
          [-clipsrcsql sql_statement] [-clipsrclayer layer]
          [-clipsrcwhere expression]
	  [-l layername]* [-where expression] [-sql select_statement]
	  [-txe xmin xmax] [-tye ymin ymax] [-outsize xsize ysize]
	  [-a algorithm[:parameter1=value1]*] [-q]
	  <src_datasource> <dst_filename>

ОПИСАНИЕ

Этот инструмент создает регулярную сеть (растр) из рассеянных данных считываемых из источника данных OGR. Для заполнения ячеек сети значениями исходные данные интерполируются, можно выбирать разные методы интерполяции.

Начиная с GDAL 1.10, можно использовать опцию GDAL_NUM_THREADS для распараллеливания вычислений. Настройка может принимать значение количества рабочих нитей или ALL_CPUS, если можно использовать все доступные ядра/процессоры.

-ot type:
Тип данных выходных растров.

-of format:
Выбор выходного формата. Формат по умолчанию - GeoTIFF (GTiff). Используйте короткое имя формата.

-txe xmin xmax:
Установить спроецированное значение ширины охвата выходного файла.

-tye ymin ymax:
Установить спроецированное значение высоты охвата выходного файла.

-outsize xsize ysize:
Установить размер выходного файла в пикселях и линиях.

-a_srs srs_def:
Игнорировать проекцию выходного файла. Значение srs_def может быть записано в обычной для GDAL/OGR форме, такой как полный WKT, PROJ.4, EPSG:n или файл содержащий WKT.

-zfield field_name:
Указывает название поля из которого будет браться значение Z. Это значение имеет приоритет над значением Z считываемом из геометрии объекта (само собой разумеется, это верно, если у вас у геометрии есть значение Z, в противном случае, у вас нет выбора и вы должны указать название поля где содержится значение Z.

-a [algorithm[:parameter1=value1][:parameter2=value2]...]:
Задает алгорит интерполяции или название метрики и (опционально) её параметры. Подробнее см. далее разделы АЛГОРИТМЫ ИНТЕРПОЛЯЦИИ и МЕТРИКИ.

-spat xmin ymin xmax ymax:
Добавляет пространственный фильтр позволяющий использовать только объекты входящие в прямоугольник описанный как (xmin, ymin) - (xmax, ymax).

-clipsrc [xmin ymin xmax ymax]|WKT|datasource|spat_extent:
Добавляет пространственный фильтр позволяющий выбрать только значения попадающие в указанный охват (выраженный в исходной СК), геометрию WKT (POLYGON или MULTIPOLYGON), набор данных или пространственный охват указанный с помощью опции -spat если вы используете ключевое слово spat_extent. Если вы указываете набор данных, то обычно нужно также использовать комбинацию опций -clipsrclayer, -clipsrcwhere или -clipsrcsql.

-clipsrcsql sql_statement:
Выбрать нужные геометрии с помощью SQL запроса.

-clipsrclayer layername:
Выбрать именованный слой из исходного набора данных использующегося для обрезки.

-clipsrcwhere expression:
Ограничить выборку геометрий с помощью атрибутивной выборки.

-l layername:
Указывает слой или слои исходного набора данных, которые будут использоваться в качестве источника объектов. Может быть использовано несколько раз, но должно быть указано по крайней мере одно название слоя или опция -sql.

-where expression:
Опциональное выражение в стиле SQL WHERE, которое нужно применить для выборки объектов из исходного слоя или слоёв.

-sql select_statement:
Выражение на SQL, которое нужно применить к набору данных для того чтобы создать виртуальный слой объектов для обработки.

-co "NAME=VALUE":
Передача опции создания драйверу выходного формата. Опций -co может быть несколько. Список опций создания расположен в документации для каждого формата отдельно.

-q:
Подавление вывода в консоль любых сообщений, кроме сообщений об ошибках.

src_datasource:
Любой источник данных поддерживаемый OGR.

dst_filename:
Выходной файл поддерживаемый GDAL.

INTERPOLATION ALGORITHMS (Александр Мурый)

There are number of interpolation algorithms to choose from.

invdist

Inverse distance to a power. This is default algorithm. It has following parameters:

power:
Weighting power (default 2.0).
smoothing:
Smoothing parameter (default 0.0).
radius1:
The first radius (X axis if rotation angle is 0) of search ellipse. Set this parameter to zero to use whole point array. Default is 0.0.
radius2:
The second radius (Y axis if rotation angle is 0) of search ellipse. Set this parameter to zero to use whole point array. Default is 0.0.
angle:
Angle of search ellipse rotation in degrees (counter clockwise, default 0.0).
max_points:
Maximum number of data points to use. Do not search for more points than this number. This is only used if search ellipse is set (both radii are non-zero). Zero means that all found points should be used. Default is 0.
min_points:
Minimum number of data points to use. If less amount of points found the grid node considered empty and will be filled with NODATA marker. This is only used if search ellipse is set (both radii are non-zero). Default is 0.
nodata:
NODATA marker to fill empty points (default 0.0).

average

Moving average algorithm. It has following parameters:

radius1:
The first radius (X axis if rotation angle is 0) of search ellipse. Set this parameter to zero to use whole point array. Default is 0.0.
radius2:
The second radius (Y axis if rotation angle is 0) of search ellipse. Set this parameter to zero to use whole point array. Default is 0.0.
angle:
Angle of search ellipse rotation in degrees (counter clockwise, default 0.0).
min_points:
Minimum number of data points to use. If less amount of points found the grid node considered empty and will be filled with NODATA marker. Default is 0.
nodata:
NODATA marker to fill empty points (default 0.0).

Note, that it is essential to set search ellipse for moving average method. It is a window that will be averaged when computing grid nodes values.

nearest

Nearest neighbor algorithm. It has following parameters:

radius1:
The first radius (X axis if rotation angle is 0) of search ellipse. Set this parameter to zero to use whole point array. Default is 0.0.
radius2:
The second radius (Y axis if rotation angle is 0) of search ellipse. Set this parameter to zero to use whole point array. Default is 0.0.
angle:
Angle of search ellipse rotation in degrees (counter clockwise, default 0.0).
nodata:
NODATA marker to fill empty points (default 0.0).

DATA METRICS

Besides the interpolation functionality gdal_grid can be used to compute some data metrics using the specified window and output grid geometry. These metrics are:

minimum:
Minimum value found in grid node search ellipse.

maximum:
Maximum value found in grid node search ellipse.

range:
A difference between the minimum and maximum values found in grid node search ellipse.

count:
A number of data points found in grid node search ellipse.

average_distance:
An average distance between the grid node (center of the search ellipse) and all of the data points found in grid node search ellipse.

average_distance_pts:
An average distance between the data points found in grid node search ellipse. The distance between each pair of points within ellipse is calculated and average of all distances is set as a grid node value.

All the metrics have the same set of options:

radius1:
The first radius (X axis if rotation angle is 0) of search ellipse. Set this parameter to zero to use whole point array. Default is 0.0.
radius2:
The second radius (Y axis if rotation angle is 0) of search ellipse. Set this parameter to zero to use whole point array. Default is 0.0.
angle:
Angle of search ellipse rotation in degrees (counter clockwise, default 0.0).
min_points:
Minimum number of data points to use. If less amount of points found the grid node considered empty and will be filled with NODATA marker. This is only used if search ellipse is set (both radii are non-zero). Default is 0.
nodata:
NODATA marker to fill empty points (default 0.0).

READING COMMA SEPARATED VALUES

Often you have a text file with a list of comma separated XYZ values to work with (so called CSV file). You can easily use that kind of data source in gdal_grid. All you need is create a virtual dataset header (VRT) for you CSV file and use it as input datasource for gdal_grid. You can find details on VRT format at Virtual Format description page.

Here is a small example. Let we have a CSV file called dem.csv containing

Easting,Northing,Elevation
86943.4,891957,139.13
87124.3,892075,135.01
86962.4,892321,182.04
87077.6,891995,135.01
...

For above data we will create dem.vrt header with the following content:

<OGRVRTDataSource>
    <OGRVRTLayer name="dem">
        <SrcDataSource>dem.csv</SrcDataSource> 
	<GeometryType>wkbPoint</GeometryType> 
	<GeometryField encoding="PointFromColumns" x="Easting" y="Northing" z="Elevation"/> 
    </OGRVRTLayer>
</OGRVRTDataSource>

This description specifies so called 2.5D geometry with three coordinates X, Y and Z. Z value will be used for interpolation. Now you can use dem.vrt with all OGR programs (start with ogrinfo to test that everything works fine). The datasource will contain single layer called "dem" filled with point features constructed from values in CSV file. Using this technique you can handle CSV files with more than three columns, switch columns, etc.

If your CSV file does not contain column headers then it can be handled in the following way:

<GeometryField encoding="PointFromColumns" x="field_1" y="field_2" z="field_3"/>

Comma Separated Value description page contains details on CSV format supported by GDAL/OGR.

EXAMPLE

The following would create raster TIFF file from VRT datasource described in READING COMMA SEPARATED VALUES section using the inverse distance to a power method. Values to interpolate will be read from Z value of geometry record.

gdal_grid -a invdist:power=2.0:smoothing=1.0 -txe 85000 89000 -tye 894000 890000 -outsize 400 400 -of GTiff -ot Float64 -l dem dem.vrt dem.tiff

The next command does the same thing as the previous one, but reads values to interpolate from the attribute field specified with -zfield option instead of geometry record. So in this case X and Y coordinates are being taken from geometry and Z is being taken from the "Elevation" field. The GDAL_NUM_THREADS is also set to parallelize the computation.

gdal_grid -zfield "Elevation" -a invdist:power=2.0:smoothing=1.0 -txe 85000 89000 -tye 894000 890000 -outsize 400 400 -of GTiff -ot Float64 -l dem dem.vrt dem.tiff --config GDAL_NUM_THREADS ALL_CPUS