SuperAPI AI Directory

gdal

General & other

View repository

Updated 10-16 09:45

About this skill

Project URL: https://github.com/OSGeo/gdal

Official documentation: https://gdal.org/en/latest/

Source code command documentation: https://gdal.org/en/latest/programs/

License: MIT License

Overview

GDAL is the de facto standard library for geospatial data processing. It provides 50+ command-line tools, divided into two major categories:

  • OGR tools(Open Geospatial Data Model): process vector data (points, lines, polygons)
  • GDAL tools: process raster data (satellite imagery, DEM, raster maps)

Environment Preparation

Prerequisites

GDAL 3.0+ is preinstalled in the geospatial processing environments of most Linux distributions. Ensure the tools are in PATH :

gdalinfo --version   # 验证 GDAL 版本
ogrinfo --version    # 验证 OGR 版本

Installation Methods

Linux (Debian/Ubuntu)

apt-get update
apt-get install gdal-bin python3-gdal

Linux (CentOS/RHEL)

yum install gdal gdal-devel

macOS (Homebrew)

brew install gdal

Conda

conda install -c conda-forge gdal

Docker

docker run -it osgeo/gdal:latest bash

Python Bindings (Optional)

Some GDAL tools (such as gdal_calc, gdal_merge, gdal_grid, gdal_polygonize) are Python scripts and require the Python bindings to be installed:

pip install gdal
# 或
conda install -c conda-forge gdal

Core Command Structure

New-style CLI (GDAL 3.11+)

GDAL 3.11 introduced a unified CLI interface:

gdal <command> <subcommand> [options] <inputs>

Main commands:

  • gdal info - Get data information (automatically detects raster or vector)
  • gdal vector - Vector operation entry point
  • gdal raster - Raster operation entry point
  • gdal dataset - Dataset management

Traditional CLI (widely used)

ogrinfo <datasource> [layer]
ogr2ogr <output> <input> [options]
gdalinfo <raster_file>
gdal_translate <input> <output> [options]
gdalwarp <input> <output> [options]

Vector Data Tools (OGR)

1. ogrinfo - Vector data information query

Description: List and query vector data sources supported by OGR (Shapefile, GeoJSON, GeoPackage, PostGIS, etc.).

Basic Usage:

# 列出所有图层
ogrinfo mydata.shp

# 获取特定图层信息
ogrinfo mydata.shp layername -so

# JSON 格式输出(GDAL 3.7+)
ogrinfo -json mydata.shp

# 显示所有要素及其属性
ogrinfo -al -geom=YES mydata.shp

# 限制显示的要素数量
ogrinfo -al -limit 10 mydata.shp

# 按属性过滤
ogrinfo mydata.shp -where "AREA > 1000"

# SQL 查询
ogrinfo mydata.shp -sql "SELECT * FROM mydata WHERE population > 10000"

# 空间范围过滤
ogrinfo mydata.shp -spat -10 40 10 50

Key Parameters:

Parameter Description
-json JSON format output (GDAL 3.7+)
-al List all layers and their features
-so Summary only (do not display individual features)
-ro Read-only mode
-where <expr> SQL WHERE expression filtering
-sql <statement> Execute SQL statements
-spat <xmin> <ymin> <xmax> <ymax> Spatial extent filtering
-limit <n> Limit the number of features
-geom=YES|NO|SUMMARY|WKT Geometry output format
-fields=YES|NO Whether to output field values

Examples:

# 查看 GeoPackage 所有图层及要素数
ogrinfo -al -so buildings.gpkg

# 获取 PostGIS 表的 JSON 信息
ogrinfo -json "PG:dbname=mydb user=postgres" public.buildings

# 查询人口超过 100 万的城市
ogrinfo cities.shp -where "population > 1000000" -fields=YES

# 导出为 GeoJSON 字符串(用于脚本)
ogrinfo -json cities.shp | jq '.layers[0].features[0]'

2. ogr2ogr - Vector data format conversion and processing

Description: GDAL's most powerful vector tool. It can convert, reproject, filter, and merge vector data between various formats.

Basic Usage:

# 格式转换(Shapefile → GeoJSON)
ogr2ogr output.geojson input.shp

# 格式转换(Shapefile → GeoPackage)
ogr2ogr -f GPKG output.gpkg input.shp

# 重投影(WGS84 → Web Mercator)
ogr2ogr -t_srs EPSG:3857 output.shp input.shp

# 属性过滤
ogr2ogr output.shp input.shp -where "area > 1000"

# 选择特定字段
ogr2ogr output.shp input.shp -select "id,name,geometry"

# 创建空间索引
ogr2ogr output.gpkg input.shp -of GPKG

# 合并多个文件
ogr2ogr -append output.shp input1.shp
ogr2ogr -append output.shp input2.shp

# 裁剪到矩形范围
ogr2ogr output.shp input.shp -spat -10 40 10 50

# 裁剪到多边形
ogr2ogr -clipsrc clip_polygon.shp output.shp input.shp

# SQL 转换(图层名通常为文件名去除扩展名)
ogr2ogr -f GeoJSON output.geojson input.shp -sql "SELECT ST_Buffer(geometry, 100) as geom, name FROM input"

# 添加字段
ogr2ogr output.shp input.shp -sql "SELECT *, 'value' as new_field FROM input"

Key Parameters:

Parameter Description
-f <format> Output format (GeoJSON, GPKG, KML, CSV, etc.)
-t_srs <EPSG> Target coordinate reference system
-s_srs <EPSG> Source coordinate reference system
-where <expr> WHERE expression filtering
-select <cols> Select specific fields
-append Append to an existing dataset
-overwrite Overwrite the existing output file
-spat <xmin> <ymin> <xmax> <ymax> Rectangular extent clipping
-clipsrc <file> Clip with a polygon
-sql <statement> SQL query
-nln <name> Output layer name

Advanced Examples:

# 合并多个 Shapefile(同时重投影)
for file in *.shp; do
  ogr2ogr -append -t_srs EPSG:4326 merged.shp "$file"
done

# 分割大文件(按行政区划)
ogr2ogr filtered.shp input.shp -where "county='New York'"

# 添加自增 ID 字段
ogr2ogr output.shp input.shp -sql "SELECT *, FID as id FROM input"

# 转换到 CSV(用于分析)
ogr2ogr -f CSV output.csv input.shp -lco GEOMETRY=AS_WKT

# PostGIS 导入
ogr2ogr -f PostgreSQL "PG:dbname=mydb user=postgres" input.shp -nln mytable

Raster Data Tools (GDAL)

3. gdalinfo - Raster data information query

Description: Displays metadata, geographic information, band information, and statistics of raster data.

Basic usage:

# 基本信息
gdalinfo dem.tif

# JSON 输出(GDAL 3.1+)
gdalinfo -json dem.tif

# 仅显示摘要(不显示统计值)
gdalinfo -checksum dem.tif

# 显示统计信息
gdalinfo -stats dem.tif

# 显示色表
gdalinfo -checksum terrain.tif | grep -A5 "Color Table"

# 计算直方图
gdalinfo -hist image.tif

Key parameters:

Parameter Description
-json JSON format output
-stats Calculate and display statistics
-approx_stats Approximate statistics (fast)
-checksum Display checksum
-hist Display histogram
-mm Display min/max values
-noct Do not display color table

Example:

# 获取 DEM 范围和分辨率
gdalinfo dem.tif | grep -E "^Size|^Upper Left|Corner|Pixel Size"

# 获取 JSON 格式地理信息
gdalinfo -json image.tif | jq '.coordinateSystem'

# 检查数据类型和波段数
gdalinfo image.tif | grep "Type:\|Band"

4. gdal_translate - Raster format conversion and resampling

Description: Converts raster files to different formats, adjusts resolution, clips, creates scaled copies, etc.

Basic usage:

# 格式转换(GeoTIFF → PNG)
gdal_translate input.tif output.png

# 格式转换(带压缩)
gdal_translate -co COMPRESS=DEFLATE input.tif output.tif

# 重采样(降低分辨率)
gdal_translate -outsize 50% 50% input.tif output.tif

# 重采样到指定分辨率
gdal_translate -tr 10 10 input.tif output.tif

# 裁剪到范围
gdal_translate -projwin -180 90 -170 80 input.tif output.tif

# 创建缩放版本(1/4 大小)
gdal_translate -outsize 25% 25% input.tif thumbnail.tif

# 转换数据类型
gdal_translate -ot Byte input.tif output.tif

# 设置 NoData 值
gdal_translate -a_nodata 0 input.tif output.tif

# 只提取特定波段
gdal_translate -b 1 rgb.tif red.tif

Key parameters:

Parameter Description
-of <format> Output format
-outsize <xsize> <ysize> Output size (pixels or percentage)
-tr <xres> <yres> Target resolution
-projwin <ulx> <uly> <lrx> <lry> Clip extent
-ot <datatype> Output data type
-b <band> Select bands
-a_nodata <value> Set NoData value
-co <NAME>=<VALUE> Creation options (e.g., compression)

5. gdalwarp - Raster reprojection and mosaicking

Description: Reprojects rasters, clips, merges multiple rasters (mosaicking), and resamples.

Basic usage:

# 重投影(UTM 50N → WGS84)
gdalwarp -t_srs EPSG:4326 input_utm.tif output_wgs84.tif

# 镶嵌多个文件
gdalwarp input1.tif input2.tif input3.tif output_mosaic.tif

# 重采样并重投影
gdalwarp -tr 30 30 -t_srs EPSG:4326 input.tif output.tif

# 裁剪(指定范围)
gdalwarp -te -10 40 10 50 input.tif output.tif

# 用矢量边界裁剪
gdalwarp -cutline clip_boundary.shp -crop_to_cutline input.tif output.tif

# 最近邻重采样(用于分类数据)
gdalwarp -r near input.tif output.tif

# 双线性插值(用于连续数据)
gdalwarp -r bilinear input.tif output.tif

# 立方卷积插值(高质量)
gdalwarp -r cubic input.tif output.tif

# 多线程处理
gdalwarp -wm 512 -co COMPRESS=DEFLATE input.tif output.tif

Key parameters:

Parameter Description
-t_srs <EPSG> Target coordinate reference system
-s_srs <EPSG> Source coordinate reference system
-tr <xres> <yres> Target resolution
-te <xmin> <ymin> <xmax> <ymax> Target extent
-cutline <file> Clip with vector boundary
-crop_to_cutline Automatically clip to boundary
-r {near|bilinear|cubic|cubicspline|lanczos} Resampling algorithm
-wm <megabytes> Working memory size
-co <NAME>=<VALUE> Creation options
-multi Multithreaded processing

6. gdal_merge.py - Raster mosaicking and merging

Description: Merges multiple rasters into a single file. Similar to gdalwarp , but simpler and does not support reprojection.

Basic usage:

# 基本合并
gdal_merge.py -o output.tif input1.tif input2.tif input3.tif

# 指定输出格式
gdal_merge.py -of JPEG -o output.jpg *.tif

# 设置像素大小
gdal_merge.py -ps 30 30 -o output.tif *.tif

# 分离波段(创建多波段文件)
gdal_merge.py -separate -o rgb.tif r.tif g.tif b.tif

# 设置 NoData 值
gdal_merge.py -n 0 -o output.tif *.tif

# 指定输出范围
gdal_merge.py -ul_lr -180 90 180 -90 -o output.tif *.tif

# 初始化像素值
gdal_merge.py -init 255 -o output.tif input1.tif input2.tif

Key parameters:

Parameter Description
-o <filename> Output file name
-of <format> Output format
-ps <pixelsize_x> <pixelsize_y> Pixel size
-tap Target aligned pixels
-separate Separate bands into different output bands
-n <nodata> Input NoData value
-a_nodata <value> Output NoData value
-ul_lr <ulx> <uly> <lrx> <lry> Output extent
-init <value> Initialize pixel value

7. gdal_calc.py - Raster calculator

Description: Performs raster mathematical operations using NumPy syntax. Supports logical and arithmetic operations.

Basic usage:

# 两个栅格平均
gdal_calc.py -A input1.tif -B input2.tif --calc="(A+B)/2" --outfile=mean.tif

# 计算 NDVI(植被指数)
gdal_calc.py -A nir.tif -B red.tif \
  --calc="(A-B)/(A+B)" --outfile=ndvi.tif

# 三个栅格相加
gdal_calc.py -A band1.tif -B band2.tif -C band3.tif \
  --calc="A+B+C" --outfile=sum.tif

# 逻辑操作(掩膜)
gdal_calc.py -A input.tif --calc="A*(A>100)" \
  --outfile=masked.tif --NoDataValue=0

# 范围选择
gdal_calc.py -A input.tif --calc="A*logical_and(A>50,A<150)" \
  --outfile=filtered.tif

# 多个表达式创建多波段输出
gdal_calc.py -A input.tif --A_band=1 -B input.tif --B_band=2 \
  --calc="(A+B)/2" --calc="B-A" --outfile=result.tif

# 处理 NoData 值
gdal_calc.py -A input.tif --hideNoData \
  --calc="A*2" --outfile=output.tif

# 转换数据类型
gdal_calc.py -A input.tif --type=Int16 \
  --calc="A.astype(numpy.int16)" --outfile=output.tif

Key parameters:

Parameter Description
-A, -B, ..., -Z <filename> Input raster (letter identifier)
--A_band=<n> Specify input band number
--calc=<expression> Calculation expression (NumPy syntax)
--outfile=<filename> Output file
--NoDataValue=<value> Output NoData value
--type=<datatype> Output data type
--format=<format> Output format
--hideNoData Ignore input NoData (participate in calculation)
--extent=union|intersect Handle rasters of different extents

8. gdal_contour - Contour extraction

Description: Extract contour lines from a DEM and generate vector lines or polygons.

Basic usage:

# 提取等高线(10 米间隔)
gdal_contour -a elevation dem.tif contours.shp -i 10

# 添加属性字段
gdal_contour -a elev dem.tif contours.shp -i 10

# 输出为 GeoJSON
gdal_contour -f GeoJSON dem.tif contours.geojson -i 50

# 生成多边形等值区域
gdal_contour -p -amin min -amax max dem.tif contour_polygons.shp -i 20

# 指定特定等高线值
gdal_contour -fl 100 200 300 dem.tif fixed_contours.shp

# 从特定波段提取
gdal_contour -b 1 dem.tif contours.shp -i 10

Key parameters:

Parameter Description
-a <name> Attribute field name (stores elevation values)
-amin <name> Polygon minimum value field
-amax <name> Polygon maximum value field
-i <interval> Contour interval
-fl <level> Fixed elevation value(s) (multiple allowed)
-off <offset> Interval offset
-p Generate polygons instead of lines
-3d Output 3D vector
-f <format> Output format
-b <band> Source band number

9. gdal_grid - Create a grid from scattered point data

Description: Create a regular grid DEM from vector point data (such as LiDAR or sample points), supporting multiple interpolation algorithms.

Basic usage:

# 基本网格化(使用平均值)
gdal_grid -a average input_points.shp output_dem.tif

# 反距离加权(IDW)插值
gdal_grid -a invdist:power=2:smoothing=0 input_points.shp output_dem.tif

# 克里金插值
gdal_grid -a kriging:variogram=spherical input_points.shp output_dem.tif

# 指定输出范围和分辨率
gdal_grid -outsize 512 512 -tr 10 10 \
  -a average input_points.shp output_dem.tif

# 只使用 Z 属性字段
gdal_grid -zfield Z -a invdist input_points.shp output_dem.tif

# 设置 NoData 值
gdal_grid -a_nodata -9999 -a average input_points.shp output_dem.tif

# 指定空间范围
gdal_grid -te 0 0 1000 1000 -a average input_points.shp output_dem.tif

Key parameters:

Parameter Description
-a <algorithm> Interpolation algorithm (average, invdist, kriging, etc.)
-zfield <name> Attribute field used for Z values
-outsize <xsize> <ysize> Output raster size
-tr <xres> <yres> Output resolution
-te <xmin> <ymin> <xmax> <ymax> Output extent
-ot <datatype> Output data type
-a_srs <srs> Output coordinate reference system
-a_nodata <value> NoData value

Supported algorithms:

  • average - Average (simplest)
  • invdist - Inverse distance weighting (commonly used)
  • invdistnn - Inverse distance weighting (nearest neighbor)
  • kriging - Kriging interpolation (advanced)
  • linear - Linear interpolation (TIN)

10. gdal_polygonize.py - Raster to vector

Description: Convert a raster to vector polygons, with each pixel value corresponding to one polygon.

Basic usage:

# 基本转换
gdal_polygonize.py input.tif output.shp

# 指定输出格式
gdal_polygonize.py input.tif -f GeoJSON output.geojson

# 转换特定波段
gdal_polygonize.py -b 1 input.tif output.shp

# 使用 8 连通性(默认 4 连通)
gdal_polygonize.py -8 input.tif output.shp

# 使用掩膜过滤
gdal_polygonize.py -mask mask.tif input.tif output.shp

# 输出到数据库
gdal_polygonize.py input.tif -f PostgreSQL \
  "PG:dbname=mydb" -nln polygons

# 自定义字段名
gdal_polygonize.py input.tif output.shp output_layer value_field

Key parameters:

Parameter Description
-b <band> Source band number
-8 Use 8-connectivity (default 4)
-mask <file> Mask file
-nomask Do not use a mask
-f <format> Output format
-nln <name> Output layer name

11. gdaltindex - Create a raster tile index

Description: Create an index for multiple raster files, generating a vector file that lists each tile's extent. Used for MapServer, etc.

Basic usage:

# 基本索引
gdaltindex index.shp *.tif

# 输出为 GeoPackage
gdaltindex -of GPKG index.gpkg *.tif

# 绝对路径
gdaltindex -write_absolute_path index.shp *.tif

# 重投影索引
gdaltindex -t_srs EPSG:4326 index.shp *.tif

# 递归搜索目录
gdaltindex -recursive -of GPKG index.gpkg /path/to/rasters/

# 使用通配符过滤
gdaltindex -filename_filter "*.tif" index.shp /data/

# 跳过不同投影的文件
gdaltindex -skip_different_projection index.shp *.tif

# 存储源 SRS 信息
gdaltindex -src_srs_name src_srs -src_srs_format EPSG index.shp *.tif

Key parameters:

Parameter Description
-of <format> Output format
-write_absolute_path Store absolute paths
-skip_different_projection Skip files with different projections
-t_srs <srs> Target projection (unify all tiles)
-src_srs_name <name> SRS field name
-recursive Recursively search directories
-filename_filter <pattern> Filename filter
-tileindex <name> Index field name (default location)

12. gdal_edit.py - Edit raster metadata

Description: Modify an existing raster's georeferencing information, coordinate system, NoData value, etc.

Basic usage:

# 设置坐标参考系
gdal_edit.py -a_srs EPSG:4326 input.tif

# 设置地理范围
gdal_edit.py -a_ullr -180 90 180 -90 input.tif

# 设置分辨率
gdal_edit.py -tr 30 30 input.tif

# 设置 NoData 值
gdal_edit.py -a_nodata 0 input.tif

# 添加地面控制点(GCP)
gdal_edit.py -gcp 0 0 -74.0 40.0 input.tif

# 添加元数据
gdal_edit.py -mo DATUM=WGS84 -mo SOURCE=USGS input.tif

# 计算并设置统计信息
gdal_edit.py -stats input.tif

# 清除地理参考
gdal_edit.py -unsetgt input.tif

# 删除 NoData 值
gdal_edit.py -unsetnodata input.tif

Key parameters:

Parameter Description
-a_srs <srs> Set coordinate reference system
-a_ullr <ulx> <uly> <lrx> <lry> Set geographic extent
-tr <xres> <yres> Set resolution
-unsetgt Remove Georeferencing
-a_nodata <value> Set NoData Value
-unsetnodata Remove NoData Value
-stats Compute Statistics
-mo <KEY>=<VALUE> Add Metadata
-gcp <pixel> <line> <x> <y> Add Ground Control Points

13. nearblack - Clean Black and White Borders

Description: Set near-black or near-white border pixels to pure black or white, used to clean up the corners of empty photos.

Basic Usage:

# 清理黑色边界(默认)
nearblack input.tif -o output.tif

# 搜索白色边界
nearblack -white input.tif -o output.tif

# 自定义颜色
nearblack -color 100,100,100 input.tif -o output.tif

# 设置容差
nearblack -near 20 input.tif -o output.tif

# 添加 Alpha 通道
nearblack -setalpha input.tif -o output.tif

# 添加掩膜波段
nearblack -setmask input.tif -o output.tif

# 指定输出格式
nearblack -of JPEG input.tif -o output.jpg

Key Parameters:

Parameter Description
-o <file> Output File
-of <format> Output Format
-white Search for White Instead of Black
-color <c1>,<c2>,... Search for a Specific Color
-near <dist> Color Tolerance (0-255, default 15)
-nb <pixels> Number of Consecutive Non-Black Pixels (default 2)
-setalpha Add Alpha Channel
-setmask Add Mask Band

Common Environment Variables and Configuration

GDAL Environment Variables

Variable Description Example
GDAL_DATA GDAL Data File Directory /usr/share/gdal/
PROJ_LIB PROJ Data File Directory /usr/share/proj/
CPL_DEBUG Debug Log Level ON / OFF
GDAL_CACHEMAX Block Cache Size (MB) 512
GDAL_NUM_THREADS Number of Threads 4 / ALL_CPUS
GDAL_DISABLE_READDIR_ON_OPEN Disable Directory Reading YES
GDAL_HTTP_TIMEOUT HTTP Timeout (seconds) 30
GDAL_HTTP_MAX_RETRY HTTP Retry Count 3
GDAL_VSI_CURL_ALLOWED_EXTENSIONS Allowed Remote File Extensions .tif,.tiff,.vrt
AWS_ACCESS_KEY_ID AWS Key ID For S3 Access
AWS_SECRET_ACCESS_KEY AWS Secret Key For S3 Access
GOOGLE_APPLICATION_CREDENTIALS Google Cloud Credentials File /path/to/credentials.json

Use Environment Variables

# 启用多线程处理
export GDAL_NUM_THREADS=ALL_CPUS

# 增加块缓存
export GDAL_CACHEMAX=1024

# 启用调试
export CPL_DEBUG=ON

# 访问 S3 上的栅格
export AWS_ACCESS_KEY_ID=xxxxx
export AWS_SECRET_ACCESS_KEY=xxxxx
gdalinfo /vsis3/bucket/key.tif

# 运行命令
gdalwarp input.tif output.tif

Data Format Support

Vector Formats

Format Extension Description
Shapefile .shp ESRI Standard Format
GeoJSON .geojson Web Standard JSON
GeoPackage .gpkg SQLite-based, recommended
KML .kml Google Maps Format
PostGIS N/A Database Vector Storage
GML .gml ISO Standard XML
CSV .csv Point Data
DXF .dxf CAD Format
MapInfo .tab MapInfo Format

Raster Formats

Format Extension Description
GeoTIFF .tif, .tiff Standard Geographic Raster (recommended)
PNG .png Web Image
JPEG .jpg, .jpeg Lossy Compression
COG .tif Cloud-Optimized GeoTIFF
NetCDF .nc Scientific Data
HDF5 .h5, .he5 Multidimensional Data
ASCII Grid .asc Simple Raster (DEM)
JPEG2000 .jp2 High-Quality Compression
ECW .ecw MrSID Format

Common Usage Patterns

Pattern 1: Batch Format Conversion

#!/bin/bash
# 将目录内所有 Shapefile 转换为 GeoJSON

for shp in *.shp; do
  base="${shp%.shp}"
  ogr2ogr -f GeoJSON "$base.geojson" "$shp"
done

Pattern 2: Batch Reprojection

#!/bin/bash
# 重投影所有 GeoTIFF 为 Web Mercator (EPSG:3857)

for tif in *.tif; do
  base="${tif%.tif}"
  gdalwarp -t_srs EPSG:3857 "$tif" "${base}_3857.tif"
done

Pattern 3: Create DEM Contours

#!/bin/bash
# 从 DEM 提取等高线(10 米间隔)

gdal_contour -a elev dem.tif -i 10 contours.shp

# 转换为 GeoJSON
ogr2ogr -f GeoJSON contours.geojson contours.shp

Pattern 4: Calculate NDVI

#!/bin/bash
# 从多光谱影像计算 NDVI

gdal_calc.py \
  -A nir_band.tif \
  -B red_band.tif \
  --calc="(A-B)/(A+B)" \
  --outfile=ndvi.tif

Pattern 5: Mosaic and Reproject

#!/bin/bash
# 合并多个影像并重投影到 WGS84

gdalwarp -t_srs EPSG:4326 \
  image1.tif image2.tif image3.tif \
  output_mosaic_wgs84.tif

Pattern 6: Create Raster Tile Index

#!/bin/bash
# 为目录内所有 GeoTIFF 创建索引

gdaltindex -recursive -of GPKG \
  tile_index.gpkg /path/to/rasters/

AI Usage Recommendations

Recommended Workflow

  1. Explore Data:

    gdalinfo input.tif  # 栅格信息
    ogrinfo input.shp   # 矢量信息
    
  2. Check Supported Formats and Drivers:

    gdalinfo --formats
    ogrinfo --formats
    
  3. Step-by-Step Processing(avoid large memory operations):

    # 不要直接镶嵌所有文件
    # 改为逐个处理和合并
    
  4. Use JSON Output(easy to parse):

    gdalinfo -json input.tif | jq '.coordinateSystem'
    ogrinfo -json input.shp | jq '.layers[0].featureCount'
    
  5. Optimize Performance:

    # 启用多线程、内存缓存、COG 格式
    export GDAL_NUM_THREADS=ALL_CPUS
    export GDAL_CACHEMAX=2048
    

Key precautions

  • Always back up: GDAL can modify files in place (such as gdal_edit.py)
  • Use absolute paths: avoid working directory issues
  • Verify coordinate systems: confirm source and target coordinate systems before reprojecting
  • Test with small data: test with a small sample before running on large datasets
  • Use VRT (Virtual Dataset): avoid creating multiple copies
  • Environment variables: set appropriate GDAL_CACHEMAX and GDAL_NUM_THREADS

Reference links