GDAL瓦片生成工具 - 中文翻译文档
1. gdal2tiles.py - 瓦片地图服务生成器
1.1 文件头部说明
python
# ******************************************************************************
#
# 项目: Google Summer of Code 2007, 2008 (http://code.google.com/soc/)
# 支持: BRGM (http://www.brgm.fr)
# 目的: 将栅格转换为TMS(瓦片地图服务)瓦片并保存到目录。
# - 生成Google Earth元数据(KML SuperOverlay)
# - 基于Google Maps和OpenLayers生成简单HTML查看器
# - 支持全局瓦片,以便与类似Google Maps的交互式网络地图兼容
# 作者: Klokan Petr Pridal, klokan at klokan dot cz
#
###############################################################################
# 版权所有 (c) 2008, Klokan Petr Pridal
# 版权所有 (c) 2010-2013, Even Rouault <even dot rouault at spatialys.com>
# 版权所有 (c) 2021, Idan Miara <idan@miara.com>
#
# SPDX-License-Identifier: MIT
# ******************************************************************************中文翻译:
# ******************************************************************************
#
# 项目: Google Summer of Code 2007, 2008
# 支持: BRGM (法国地质调查局)
# 目的: 将栅格数据转换为TMS(瓦片地图服务)瓦片并保存到目录。
# - 生成Google Earth元数据(KML超图层)
# - 基于Google Maps和OpenLayers生成简单HTML查看器
# - 支持全局瓦片,以便与类似Google Maps的交互式网络地图兼容
# 作者: Klokan Petr Pridal, klokan at klokan dot cz
#
###############################################################################
# 版权所有 (c) 2008, Klokan Petr Pridal
# 版权所有 (c) 2010-2013, Even Rouault <even dot rouault at spatialys.com>
# 版权所有 (c) 2021, Idan Miara <idan@miara.com>
#
# SPDX-License-Identifier: MIT
# ******************************************************************************1.2 主要类说明
GlobalMercator - 全局墨卡托投影
python
class GlobalMercator:
r"""
TMS全局墨卡托配置
---------------------------
生成球面墨卡托投影(EPSG:3857)瓦片所需的功能。
这些瓦片与Google Maps、Bing Maps、Yahoo Maps兼容,
英国Ordnance Survey OpenSpace API等,
并且您可以将其叠加在这些Web地图应用的基础地图上。
像素和瓦片坐标使用TMS表示法(原点在左下角)。
对于TMS全局墨卡托瓦片,我们需要哪些坐标转换:
纬度经度 <-> 米 <-> 像素 <-> 瓦片
WGS84坐标 球面墨卡托 瓦片金字塔中的像素坐标 瓦片金字塔中的瓦片
纬度/经度 米制XY 瓦片金字塔中的XY像素 TMS的XYZ
EPSG:4326 EPSG:3857
.----. --------- -- TMS
/ \ <-> | | <-> /----/ <-> Google
\ / | | /--------/ 四叉树
----- --------- /------------/
KML, 公共 WebMapService Web客户端 TileMapService
"""中文翻译:
python
class GlobalMercator:
r"""
TMS全局墨卡托配置
---------------------------
生成球面墨卡托投影(EPSG:3857)瓦片所需的功能。
这些瓦片与Google Maps、Bing Maps、Yahoo Maps兼容,
英国Ordnance Survey OpenSpace API等,
并且您可以将其叠加在这些Web地图应用的基础地图上。
像素和瓦片坐标使用TMS表示法(原点在左下角)。
对于TMS全局墨卡托瓦片,我们需要哪些坐标转换:
纬度经度 <-> 米 <-> 像素 <-> 瓦片
WGS84坐标 球面墨卡托 瓦片金字塔中的像素坐标 瓦片金字塔中的瓦片
纬度/经度 米制XY 瓦片金字塔中的XY像素 TMS的XYZ
EPSG:4326 EPSG:3857
.----. --------- -- TMS
/ \ <-> | | <-> /----/ <-> Google
\ / | | /--------/ 四叉树
----- --------- /------------/
KML, 公共 WebMapService Web客户端 TileMapService
"""GlobalGeodetic - 全局大地测量配置
python
class GlobalGeodetic:
r"""
TMS全局大地测量配置
---------------------------
生成Plate Carre投影的全局瓦片所需功能,
EPSG:4326,"未投影配置"。
这些瓦片与Google Earth兼容(以及任何其他EPSG:4326栅格)
并且您可以将瓦片叠加在OpenLayers基础地图上。
像素和瓦片坐标使用TMS表示法(原点在左下角)。
对于TMS全局大地测量瓦片,我们需要哪些坐标转换?
全局大地测量瓦片使用大地测量坐标(纬度、经度)
直接作为平面坐标XY(也称为未投影或Plate Carre)。
我们只需要缩放到像素金字塔并切割为瓦片。
瓦片金字塔在顶层有两个瓦片,所以不是正方形而是长方形。
区域 [-180,-90,180,90] 缩放到 512x256 像素。
TMS具有像素和瓦片的坐标原点(在左下角)。
栅格为EPSG:4326,因此与Google Earth兼容。
纬度经度 <-> 像素 <-> 瓦片
WGS84坐标 瓦片金字塔中的像素 瓦片金字塔中的瓦片
纬度/经度 XY像素 Z缩放 TMS的XYZ
EPSG:4326
.----. ----
/ \ <-> /--------/ <-> TMS
\ / /--------------/
----- /--------------------/
WMS, KML Web客户端, Google Earth TileMapService
"""中文翻译:
python
class GlobalGeodetic:
r"""
TMS全局大地测量配置
---------------------------
生成Plate Carre投影的全局瓦片所需功能,
EPSG:4326,"未投影配置"。
这些瓦片与Google Earth兼容(以及任何其他EPSG:4326栅格)
并且您可以将瓦片叠加在OpenLayers基础地图上。
像素和瓦片坐标使用TMS表示法(原点在左下角)。
对于TMS全局大地测量瓦片,我们需要哪些坐标转换?
全局大地测量瓦片使用大地测量坐标(纬度、经度)
直接作为平面坐标XY(也称为未投影或Plate Carre)。
我们只需要缩放到像素金字塔并切割为瓦片。
瓦片金字塔在顶层有两个瓦片,所以不是正方形而是长方形。
区域 [-180,-90,180,90] 缩放到 512x256 像素。
TMS具有像素和瓦片的坐标原点(在左下角)。
栅格为EPSG:4326,因此与Google Earth兼容。
纬度经度 <-> 像素 <-> 瓦片
WGS84坐标 瓦片金字塔中的像素 瓦片金字塔中的瓦片
纬度/经度 XY像素 Z缩放 TMS的XYZ
EPSG:4326
.----. ----
/ \ <-> /--------/ <-> TMS
\ / /--------------/
----- /--------------------/
WMS, KML Web客户端, Google Earth TileMapService
"""1.3 GDAL2Tiles类初始化
python
class GDAL2Tiles:
def __init__(
self, input_file: str, output_folder: str, options: Options, tmsMap: dict
) -> None:
"""Constructor function - initialization"""
self.tmsMap = tmsMap
self.out_drv = None
self.mem_drv = None
self.warped_input_dataset = None
self.out_srs = None
self.nativezoom = None
self.tminmax = None
self.tsize = None
self.mercator = None
self.geodetic = None
self.dataBandsCount = None
self.out_gt = None
self.tileswne = None
self.swne = None
self.ominx = None
self.omaxx = None
self.omaxy = None
self.ominy = None
self.input_file = None
self.output_folder = None
self.isepsg4326 = None
self.in_srs = None
self.in_srs_wkt = None
# Tile format
self.tile_size = 256
if options.tilesize:
self.tile_size = options.tilesize
self.tiledriver = options.tiledriver
if options.tiledriver == "PNG":
self.tileext = "png"
elif options.tiledriver == "WEBP":
self.tileext = "webp"
else:
self.tileext = "jpg"
if options.mpi:
makedirs(output_folder)
self.tmp_dir = tempfile.mkdtemp(dir=output_folder)
else:
self.tmp_dir = tempfile.mkdtemp()
self.tmp_vrt_filename = os.path.join(self.tmp_dir, str(uuid4()) + ".vrt")
# Should we read bigger window of the input raster and scale it down?
# Note: Modified later by open_input()
# Not for 'near' resampling
# Not for Wavelet based drivers (JPEG2000, ECW, MrSID)
# Not for 'raster' profile
self.scaledquery = True
# How big should be query window be for scaling down
# Later on reset according the chosen resampling algorithm
self.querysize = 4 * self.tile_size
# Should we use Read on the input file for generating overview tiles?
# Note: Modified later by open_input()
# Otherwise the overview tiles are generated from existing underlying tiles
self.overviewquery = False
self.input_file = input_file
self.output_folder = output_folder
self.options = options
if self.options.resampling == "near":
self.querysize = self.tile_size
elif self.options.resampling == "bilinear":
self.querysize = self.tile_size * 2
self.tminz, self.tmaxz = self.options.zoom
# KML generation
self.kml = self.options.kml中文翻译:
python
class GDAL2Tiles:
def __init__(
self, input_file: str, output_folder: str, options: Options, tmsMap: dict
) -> None:
"""构造函数 - 初始化"""
self.tmsMap = tmsMap
self.out_drv = None
self.mem_drv = None
self.warped_input_dataset = None
self.out_srs = None
self.nativezoom = None
self.tminmax = None
self.tsize = None
self.mercator = None
self.geodetic = None
self.dataBandsCount = None
self.out_gt = None
self.tileswne = None
self.swne = None
self.ominx = None
self.omaxx = None
self.omaxy = None
self.ominy = None
self.input_file = None
self.output_folder = None
self.isepsg4326 = None
self.in_srs = None
self.in_srs_wkt = None
# 瓦片格式
self.tile_size = 256
if options.tilesize:
self.tile_size = options.tilesize
self.tiledriver = options.tiledriver
if options.tiledriver == "PNG":
self.tileext = "png"
elif options.tiledriver == "WEBP":
self.tileext = "webp"
else:
self.tileext = "jpg"
if options.mpi:
makedirs(output_folder)
self.tmp_dir = tempfile.mkdtemp(dir=output_folder)
else:
self.tmp_dir = tempfile.mkdtemp()
self.tmp_vrt_filename = os.path.join(self.tmp_dir, str(uuid4()) + ".vrt")
# 是否读取输入栅格的更大窗口并缩放?
# 注意:由open_input()后续修改
# 不适用于'near'重采样
# 不适用于基于小波的驱动程序(JPEG2000, ECW, MrSID)
# 不适用于'raster'配置
self.scaledquery = True
# 缩放时查询窗口应该多大
# 后续根据选定的重采样算法重置
self.querysize = 4 * self.tile_size
# 是否使用Read读取输入文件来生成概览瓦片?
# 注意:由open_input()后续修改
# 否则概览瓦片从现有的底层瓦片生成
self.overviewquery = False
self.input_file = input_file
self.output_folder = output_folder
self.options = options
if self.options.resampling == "near":
self.querysize = self.tile_size
elif self.options.resampling == "bilinear":
self.querysize = self.tile_size * 2
self.tminz, self.tmaxz = self.options.zoom
# KML生成
self.kml = self.options.kml1.4 输入文件处理
python
# -------------------------------------------------------------------------
def open_input(self) -> None:
"""Initialization of the input raster, reprojection if necessary"""
gdal.AllRegister()
self.out_drv = gdal.GetDriverByName(self.tiledriver)
self.mem_drv = gdal.GetDriverByName("MEM")
if not self.out_drv:
raise Exception(
"The '%s' driver was not found, is it available in this GDAL build?"
% self.tiledriver
)
if not self.mem_drv:
raise Exception(
"The 'MEM' driver was not found, is it available in this GDAL build?"
)
# Open the input file
if self.input_file:
input_dataset: gdal.Dataset = gdal.Open(self.input_file, gdal.GA_ReadOnly)
else:
raise Exception("No input file was specified")
if self.options.verbose:
logger.debug(
"Input file: (%dP x %dL - %d bands)"
% (
input_dataset.RasterXSize,
input_dataset.RasterYSize,
input_dataset.RasterCount,
),
)
if not input_dataset:
# Note: GDAL prints the ERROR message too
exit_with_error(
"It is not possible to open the input file '%s'." % self.input_file
)
# Read metadata from the input file
if input_dataset.RasterCount == 0:
exit_with_error("Input file '%s' has no raster band" % self.input_file)
if input_dataset.GetRasterBand(1).GetRasterColorTable():
exit_with_error(
"Please convert this file to RGB/RGBA and run gdal2tiles on the result.",
"From paletted file you can create RGBA file (temp.vrt) by:\n"
"gdal_translate -of vrt -expand rgba %s temp.vrt\n"
"then run:\n"
"gdal2tiles temp.vrt" % self.input_file,
)
if input_dataset.GetRasterBand(1).DataType != gdal.GDT_Byte:
exit_with_error(
"Please convert this file to 8-bit and run gdal2tiles on the result.",
"To scale pixel values you can use:\n"
"gdal_translate -of VRT -ot Byte -scale %s temp.vrt\n"
"then run:\n"
"gdal2tiles temp.vrt" % self.input_file,
)
in_nodata = setup_no_data_values(input_dataset, self.options)中文翻译:
python
# -------------------------------------------------------------------------
def open_input(self) -> None:
"""初始化输入栅格,如需要则进行投影转换"""
gdal.AllRegister()
self.out_drv = gdal.GetDriverByName(self.tiledriver)
self.mem_drv = gdal.GetDriverByName("MEM")
if not self.out_drv:
raise Exception(
"未找到 '%s' 驱动,是否在当前GDAL构建中可用?"
% self.tiledriver
)
if not self.mem_drv:
raise Exception(
"未找到 'MEM' 驱动,是否在当前GDAL构建中可用?"
)
# 打开输入文件
if self.input_file:
input_dataset: gdal.Dataset = gdal.Open(self.input_file, gdal.GA_ReadOnly)
else:
raise Exception("未指定输入文件")
if self.options.verbose:
logger.debug(
"输入文件: (%d像素宽 x %d像素长 - %d个波段)"
% (
input_dataset.RasterXSize,
input_dataset.RasterYSize,
input_dataset.RasterCount,
),
)
if not input_dataset:
# 注意:GDAL也会打印错误消息
exit_with_error(
"无法打开输入文件 '%s'。" % self.input_file
)
# 从输入文件读取元数据
if input_dataset.RasterCount == 0:
exit_with_error("输入文件 '%s' 没有栅格波段" % self.input_file)
if input_dataset.GetRasterBand(1).GetRasterColorTable():
exit_with_error(
"请将此文件转换为RGB/RGBA并运行gdal2tiles。",
"从调色板文件,您可以通过以下方式创建RGBA文件(temp.vrt):\n"
"gdal_translate -of vrt -expand rgba %s temp.vrt\n"
"然后运行:\n"
"gdal2tiles temp.vrt" % self.input_file,
)
if input_dataset.GetRasterBand(1).DataType != gdal.GDT_Byte:
exit_with_error(
"请将此文件转换为8位并运行gdal2tiles。",
"要缩放像素值,您可以使用:\n"
"gdal_translate -of VRT -ot Byte -scale %s temp.vrt\n"
"然后运行:\n"
"gdal2tiles temp.vrt" % self.input_file,
)
in_nodata = setup_no_data_values(input_dataset, self.options)1.5 瓦片生成
python
def generate_base_tiles(self) -> Tuple[TileJobInfo, List[TileDetail]]:
"""
Generation of the base tiles (the lowest in the pyramid) directly from the input raster
"""
if not self.options.quiet:
logger.info("Generating Base Tiles:")
if self.options.verbose:
logger.debug("")
logger.debug("Tiles generated from the max zoom level:")
logger.debug("----------------------------------------")
logger.debug("")
# Set the bounds
tminx, tminy, tmaxx, tmaxy = self.tminmax[self.tmaxz]
ds = self.warped_input_dataset
tilebands = self.dataBandsCount + 1
querysize = self.querysize
if self.options.verbose:
logger.debug("dataBandsCount: %d" % self.dataBandsCount)
logger.debug("tilebands: %d" % tilebands)
tcount = (1 + abs(tmaxx - tminx)) * (1 + abs(tmaxy - tminy))
ti = 0
tile_details = []
tz = self.tmaxz
# Create directories for the tiles
for tx in range(tminx, tmaxx + 1):
tiledirname = os.path.join(self.output_folder, str(tz), str(tx))
makedirs(tiledirname)
for ty in range(tmaxy, tminy - 1, -1):
for tx in range(tminx, tmaxx + 1):
ti += 1
ytile = GDAL2Tiles.getYTile(ty, tz, self.options, self.tmsMap)
tilefilename = os.path.join(
self.output_folder,
str(tz),
str(tx),
"%s.%s" % (ytile, self.tileext),
)
if self.options.verbose:
logger.debug("%d / %d, %s" % (ti, tcount, tilefilename))中文翻译:
python
def generate_base_tiles(self) -> Tuple[TileJobInfo, List[TileDetail]]:
"""
直接从输入栅格生成基础瓦片(金字塔中的最低层)
"""
if not self.options.quiet:
logger.info("生成基础瓦片:")
if self.options.verbose:
logger.debug("")
logger.debug("从最大缩放级别生成瓦片:")
logger.debug("----------------------------------------")
logger.debug("")
# 设置边界
tminx, tminy, tmaxx, tmaxy = self.tminmax[self.tmaxz]
ds = self.warped_input_dataset
tilebands = self.dataBandsCount + 1
querysize = self.querysize
if self.options.verbose:
logger.debug("dataBandsCount: %d" % self.dataBandsCount)
logger.debug("tilebands: %d" % tilebands)
tcount = (1 + abs(tmaxx - tminx)) * (1 + abs(tmaxy - tminy))
ti = 0
tile_details = []
tz = self.tmaxz
# 为瓦片创建目录
for tx in range(tminx, tmaxx + 1):
tiledirname = os.path.join(self.output_folder, str(tz), str(tx))
makedirs(tiledirname)
for ty in range(tmaxy, tminy - 1, -1):
for tx in range(tminx, tmaxx + 1):
ti += 1
ytile = GDAL2Tiles.getYTile(ty, tz, self.options, self.tmsMap)
tilefilename = os.path.join(
self.output_folder,
str(tz),
str(tx),
"%s.%s" % (ytile, self.tileext),
)
if self.options.verbose:
logger.debug("%d / %d, %s" % (ti, tcount, tilefilename))2. gdal2xyz.py - 栅格到XYZ点流转换器
2.1 函数说明
python
@enable_gdal_exceptions
def gdal2xyz(
srcfile: PathOrDS,
dstfile: PathLikeOrStr = None,
srcwin: Optional[Sequence[int]] = None,
skip: Union[int, Sequence[int]] = 1,
band_nums: Optional[Sequence[int]] = None,
delim: str = " ",
skip_nodata: bool = False,
src_nodata: Optional[Union[Sequence, Number]] = None,
dst_nodata: Optional[Union[Sequence, Number]] = None,
return_np_arrays: bool = False,
pre_allocate_np_arrays: bool = True,
progress_callback: OptionalProgressCallback = ...,
) -> Optional[Tuple]:
"""
translates a raster file (or dataset) into xyz format
skip - how many rows/cols to skip each iteration
srcwin (xoff, yoff, xsize, ysize) - Selects a subwindow from the source image for copying based on pixel/line location.
band_nums - selected input bands to process, None to process all.
delim - the delimiter to use between values in a line
skip_nodata - Exclude the output lines with nodata value (as determined by srcnodata)
src_nodata - The nodata value of the dataset (for skipping or replacing)
default (`None`) - Use the dataset NoDataValue;
`Sequence`/`Number` - use the given nodata value (per band or per dataset).
dst_nodata - Replace source nodata with a given nodata. Has an effect only if not setting `-skipnodata`
default(`None`) - use srcnodata, no replacement;
`Sequence`/`Number` - replace the `srcnodata` with the given nodata value (per band or per dataset).
srcfile - The source dataset filename or dataset object
dstfile - The output dataset filename; for dstfile=None - if return_np_arrays=False then output will be printed to stdout
return_np_arrays - return numpy arrays of the result, otherwise returns None
pre_allocate_np_arrays - pre-allocated result arrays.
Should be faster unless skip_nodata and the input is very sparse thus most data points will be skipped.
progress_callback - progress callback function. use None for quiet or Ellipsis for using the default callback
"""中文翻译:
python
@enable_gdal_exceptions
def gdal2xyz(
srcfile: PathOrDS,
dstfile: PathLikeOrStr = None,
srcwin: Optional[Sequence[int]] = None,
skip: Union[int, Sequence[int]] = 1,
band_nums: Optional[Sequence[int]] = None,
delim: str = " ",
skip_nodata: bool = False,
src_nodata: Optional[Union[Sequence, Number]] = None,
dst_nodata: Optional[Union[Sequence, Number]] = None,
return_np_arrays: bool = False,
pre_allocate_np_arrays: bool = True,
progress_callback: OptionalProgressCallback = ...,
) -> Optional[Tuple]:
"""
将栅格文件(或数据集)转换为XYZ格式
skip - 每次迭代跳过多少行/列
srcwin (xoff, yoff, xsize, ysize) - 根据像素/行位置从源图像中选择子窗口用于复制
band_nums - 要处理的选定输入波段,None表示处理所有波段
delim - 一行中值之间使用的分隔符
skip_nodata - 排除具有nodata值的输出行(根据srcnodata确定)
src_nodata - 数据集的nodata值(用于跳过或替换)
默认(`None`)- 使用数据集NoDataValue
`Sequence`/`Number` - 使用给定的nodata值(每波段或每数据集)
dst_nodata - 用给定的nodata替换源nodata。仅在未设置`-skipnodata`时有效
默认(`None`)- 使用srcnodata,不替换
`Sequence`/`Number` - 用给定的nodata值替换`srcnodata`(每波段或每数据集)
srcfile - 源数据集文件名或数据集对象
dstfile - 输出数据集文件名;对于dstfile=None,如果return_np_arrays=False则输出将打印到stdout
return_np_arrays - 返回结果的numpy数组,否则返回None
pre_allocate_np_arrays - 预分配结果数组
通常更快,除非skip_nodata且输入非常稀疏,大多数数据点将被跳过
progress_callback - 进度回调函数。使用None表示静默模式,使用Ellipsis表示使用默认回调
"""2.2 类说明
python
class GDAL2XYZ(GDALScript):
def __init__(self):
super().__init__()
self.title = "Translates a raster file into xyz format"
self.description = textwrap.dedent("""\
The gdal2xyz utility can be used to translate a raster file into xyz format.
It can be used as an alternative to gdal_translate of=xyz,
But supporting other options, for example:
* Select more then one band;
* Skip or replace nodata value;
* Return the output as numpy arrays.""")中文翻译:
python
class GDAL2XYZ(GDALScript):
def __init__(self):
super().__init__()
self.title = "将栅格文件转换为xyz格式"
self.description = textwrap.dedent("""\
gdal2xyz实用程序可用于将栅格文件转换为xyz格式。
它可以用作gdal_translate of=xyz的替代方案,
但支持其他选项,例如:
* 选择多个波段;
* 跳过或替换nodata值;
* 将输出作为numpy数组返回。""")2.3 参数说明
python
parser.add_argument(
"-skip",
dest="skip",
action="store_true",
default=1,
help="How many rows/cols to skip in each iteration.",
)
parser.add_argument(
"-srcwin",
metavar=("xoff", "yoff", "xsize", "ysize"),
dest="srcwin",
type=int,
nargs=4,
help="Selects a subwindow from the source image for copying based on pixel/line location",
)
parser.add_argument(
"-b",
"-band",
"--band",
dest="band_nums",
metavar="band",
type=int,
nargs="+",
help="Select bands from the input spectral bands for output. "
"Bands are numbered from 1 in the order spectral bands are specified. "
"Multiple -b switches may be used. When no -b switch is used, the first band will be used."
"In order to use all input bands set -allbands or -b 0..",
)
parser.add_argument(
"-allbands",
"--allbands",
dest="allbands",
action="store_true",
help="Select all input bands.",
)
parser.add_argument(
"-csv",
dest="delim",
const=",",
default=" ",
action="const",
help="Use comma instead of space as a delimiter.",
)
parser.add_argument(
"-skipnodata",
"--skipnodata",
"-skip_nodata",
dest="skip_nodata",
action="store_true",
help="Exclude the output lines with nodata value (as determined by srcnodata).",
)
parser.add_argument(
"-srcnodata",
"-nodatavalue",
dest="src_nodata",
type=float,
nargs="*",
help="The nodata value of the dataset (for skipping or replacing) "
"Default (None) - Use the dataset nodata value; "
"Sequence/Number - Use the given nodata value (per band or per dataset).",
)
parser.add_argument(
"-dstnodata",
dest="dst_nodata",
type=float,
nargs="*",
help="Replace source nodata with a given nodata. "
"Has an effect only if not setting -skipnodata. "
"Default(None) - Use srcnodata, no replacement; "
"Sequence/Number - Replace the srcnodata with the given nodata value "
"(per band or per dataset).",
)
parser.add_argument(
"srcfile",
metavar="src_dataset",
type=str,
help="The source dataset name. It can be either file name, "
"URL of data source or subdataset name for multi-dataset files.",
)
parser.add_argument(
"dstfile",
metavar="dst_dataset",
type=str,
help="The destination file name.",
)中文翻译:
python
parser.add_argument(
"-skip",
dest="skip",
action="store_true",
default=1,
help="每次迭代跳过多少行/列。",
)
parser.add_argument(
"-srcwin",
metavar=("xoff", "yoff", "xsize", "ysize"),
dest="srcwin",
type=int,
nargs=4,
help="根据像素/行位置从源图像中选择子窗口用于复制",
)
parser.add_argument(
"-b",
"-band",
"--band",
dest="band_nums",
metavar="band",
type=int,
nargs="+",
help="从输入光谱波段中选择波段进行输出。"
"波段编号从1开始,按照指定顺序。"
"可以使用多个-b开关。如果没有使用-b开关,将使用第一个波段。"
"要使用所有输入波段,请设置-allbands或-b 0..",
)
parser.add_argument(
"-allbands",
"--allbands",
dest="allbands",
action="store_true",
help="选择所有输入波段。",
)
parser.add_argument(
"-csv",
dest="delim",
const=",",
default=" ",
action="const",
help="使用逗号代替空格作为分隔符。",
)
parser.add_argument(
"-skipnodata",
"--skipnodata",
"-skip_nodata",
dest="skip_nodata",
action="store_true",
help="排除具有nodata值的输出行(根据srcnodata确定)。",
)
parser.add_argument(
"-srcnodata",
"-nodatavalue",
dest="src_nodata",
type=float,
nargs="*",
help="数据集的nodata值(用于跳过或替换)"
"默认值- 使用数据集nodata值;"
"Sequence/Number - 使用给定的nodata值(每波段或每数据集)。",
)
parser.add_argument(
"-dstnodata",
dest="dst_nodata",
type=float,
nargs="*",
help="用给定的nodata替换源nodata。"
"仅在未设置-skipnodata时有效。"
"默认值- 使用srcnodata,不替换;"
"Sequence/Number - 用给定的nodata值替换srcnodata"
"(每波段或每数据集)。",
)
parser.add_argument(
"srcfile",
metavar="src_dataset",
type=str,
help="源数据集名称。可以是文件名、"
"数据源URL或多数据集文件的子数据集名称。",
)
parser.add_argument(
"dstfile",
metavar="dst_dataset",
type=str,
help="目标文件名。",
)3. 主要函数翻译
3.1 makedirs - 创建目录包装器
python
def makedirs(path):
"""Wrapper for os.makedirs() that can work with /vsi files too"""
if path.startswith("/vsi"):
if gdal.MkdirRecursive(path, 0o755) != 0:
raise Exception(f"Cannot create {path}")
else:
os.makedirs(path, exist_ok=True)中文翻译:
python
def makedirs(path):
"""支持/vsi文件的os.makedirs()包装器"""
if path.startswith("/vsi"):
if gdal.MkdirRecursive(path, 0o755) != 0:
raise Exception(f"无法创建 {path}")
else:
os.makedirs(path, exist_ok=True)3.2 isfile - 文件存在检查
python
def isfile(path):
"""Wrapper for os.path.isfile() that can work with /vsi files too"""
if path.startswith("/vsi"):
stat_res = gdal.VSIStatL(path)
if stat_res is None:
return False
return stat.S_ISREG(stat_res.mode)
else:
return os.path.isfile(path)中文翻译:
python
def isfile(path):
"""支持/vsi文件的os.path.isfile()包装器"""
if path.startswith("/vsi"):
stat_res = gdal.VSIStatL(path)
if stat_res is None:
return False
return stat.S_ISREG(stat_res.mode)
else:
return os.path.isfile(path)3.3 scale_query_to_tile - 查询集缩放到瓦片
python
def scale_query_to_tile(dsquery, dstile, options, tilefilename=""):
"""Scales down query dataset to the tile dataset"""
querysize = dsquery.RasterXSize
tile_size = dstile.RasterXSize
tilebands = dstile.RasterCount
dsquery.SetGeoTransform(
(
0.0,
tile_size / float(querysize),
0.0,
0.0,
0.0,
tile_size / float(querysize),
)
)
dstile.SetGeoTransform((0.0, 1.0, 0.0, 0.0, 0.0, 1.0))
if options.resampling == "average" and (
options.excluded_values or options.nodata_values_pct_threshold < 100
):
warp_options = "-r average"
assert options.nodata_values_pct_threshold is not None
warp_options += (
f" -wo NODATA_VALUES_PCT_THRESHOLD={options.nodata_values_pct_threshold}"
)
if options.excluded_values:
assert options.excluded_values_pct_threshold is not None
warp_options += f" -wo EXCLUDED_VALUES={options.excluded_values}"
warp_options += f" -wo EXCLUDED_VALUES_PCT_THRESHOLD={options.excluded_values_pct_threshold}"
gdal.Warp(
dstile,
dsquery,
options=warp_options,
)中文翻译:
python
def scale_query_to_tile(dsquery, dstile, options, tilefilename=""):
"""将查询数据集缩放到瓦片数据集"""
querysize = dsquery.RasterXSize
tile_size = dstile.RasterXSize
tilebands = dstile.RasterCount
dsquery.SetGeoTransform(
(
0.0,
tile_size / float(querysize),
0.0,
0.0,
0.0,
tile_size / float(querysize),
)
)
dstile.SetGeoTransform((0.0, 1.0, 0.0, 0.0, 0.0, 1.0))
if options.resampling == "average" and (
options.excluded_values or options.nodata_values_pct_threshold < 100
):
warp_options = "-r average"
assert options.nodata_values_pct_threshold is not None
warp_options += (
f" -wo NODATA_VALUES_PCT_THRESHOLD={options.nodata_values_pct_threshold}"
)
if options.excluded_values:
assert options.excluded_values_pct_threshold is not None
warp_options += f" -wo EXCLUDED_VALUES={options.excluded_values}"
warp_options += f" -wo EXCLUDED_VALUES_PCT_THRESHOLD={options.excluded_values_pct_threshold}"
gdal.Warp(
dstile,
dsquery,
options=warp_options,
)4. 主要选项说明
4.1 gdal2tiles.py 主要选项
| 选项 | 说明 | 中文翻译 |
|---|---|---|
-p, --profile | 瓦片切割配置 | 瓦片切割配置 |
-r, --resampling | 重采样方法 | 重采样方法 |
-s, --s_srs | 源数据的空间参考系统 | 源数据的空间参考系统 |
-z, --zoom | 缩放级别范围 | 缩放级别范围 |
-e, --resume | 恢复模式,只生成缺失文件 | 恢复模式,仅生成缺失文件 |
-a, --srcnodata | 输入数据集中视为透明的值 | 输入数据集中视为透明的数据集值 |
-d, --tmscompatible | 指定geodetic配置的基准分辨率 | 指定geodetic配置的基准分辨率 |
--xyz | 使用XYZ瓦片编号(OSM滑块地图) | 使用XYZ瓦片编号(OSM滑块地图) |
-v, --verbose | 打印状态消息到stdout | 将状态消息打印到stdout |
-x, --exclude | 从结果瓦片集中排除透明瓦片 | 从结果瓦片集中排除透明瓦片 |
--processes | 用于瓦片化的进程数 | 用于瓦片化的进程数 |
--tilesize | 瓦片的宽度和高度(像素) | 瓦片的宽度和高度(像素) |
--tiledriver | 用于瓦片的驱动程序 | 用于瓦片的驱动程序 |
-k, --force-kml | 为Google Earth生成KML | 为Google Earth生成KML |
-w, --webviewer | 生成查看器类型 | 生成查看器类型 |
4.2 gdal2xyz.py 主要选项
| 选项 | 说明 | 中文翻译 |
|---|---|---|
-skip | 每次迭代跳过的行/列数 | 每次迭代跳过的行/列数 |
-srcwin | 根据像素/行位置选择子窗口 | 根据像素/行位置选择子窗口 |
-b, -band, --band | 从输入波段中选择波段 | 从输入波段中选择波段 |
-allbands | 选择所有输入波段 | 选择所有输入波段 |
-csv | 使用逗号作为分隔符 | 使用逗号作为分隔符 |
-skipnodata | 排除具有nodata值的输出行 | 排除具有nodata值的输出行 |
-srcnodata, -nodatavalue | 数据集的nodata值 | 数据集的nodata值 |
-dstnodata | 用给定的nodata替换源nodata | 用给定的nodata替换源nodata |
5. 技术术语对照表
空间参考系统相关
- Spatial Reference System (SRS): 空间参考系统
- EPSG: European Petroleum Survey Group (欧洲石油调查组织)
- WGS84: World Geodetic System 1984 (世界大地测量系统1984)
- Projection: 投影
- Datum: 大地基准
- Coordinate Transformation: 坐标转换
瓦片相关
- Tile: 瓦片
- Tile Map Service (TMS): 瓦片地图服务
- XYZ Tile Numbering: XYZ瓦片编号
- QuadTree: 四叉树
- Zoom Level: 缩放级别
- Tile Size: 瓦片大小
- Resolution: 分辨率
- Pyramid: 金字塔(多级瓦片结构)
重采样相关
- Resampling: 重采样
- Nearest Neighbor: 最近邻
- Bilinear: 双线性
- Cubic: 三次
- Lanczos: Lanczos滤波
- Average: 平均值
栅格数据相关
- Raster: 栅格
- Band: 波段
- Pixel: 像素
- NoData Value: 无数据值
- Alpha Channel: 透明通道
- Geotransform: 地理变换参数
- GCP (Ground Control Point): 地面控制点
网络地图相关
- Google Maps: 谷歌地图
- OpenLayers: OpenLayers库
- Leaflet: Leaflet库
- KML: Keyhole Markup Language(谷歌地球格式)
- HTML Viewer: HTML查看器
- Base Layer: 底图层
- Overlay Layer: 覆盖层
其他技术术语
- GDAL: Geospatial Data Abstraction Library (地理空间数据抽象库)
- VRT: Virtual Raster (虚拟栅格)
- Spherical Mercator: 球面墨卡托投影
- Plate Carre: 平板Carre投影(未投影配置)
- WorldCRS84Quad: 世界CRS84四边形
- GlobalGeodeticOriginLat270: 全局大地测量原点纬度270
6. 常见使用场景
6.1 生成Web地图瓦片
bash
# 生成Mercator配置的瓦片
gdal2tiles input.tif output_dir
# 指定输出格式为JPEG
gdal2tiles -tiledriver JPEG input.tif output_dir
# 指定缩放级别
gdal2tiles -z 0-10 input.tif output_dir
# 生成KML文件用于Google Earth
gdal2tiles -k input.tif output_dir6.2 从RGB图像生成瓦片
bash
# 首先将RGB转换为RGBA
gdal_translate -of VRT -expand rgba input.tif output_rgba.vrt
# 然后生成瓦片
gdal2tiles output_rgba.vrt output_dir6.3 转换为XYZ点流
bash
# 将栅格转换为XYZ格式
gdal2xyz input.tif output.xyz
# 选择特定波段
gdal2xyz -b 1 -b 2 input.tif output.xyz
# 跳过nodata值
gdal2xyz -skipnodata input.tif output.xyz
# 返回numpy数组
python -c "from gdal2xyz import gdal2xyz; result = gdal2xyz('input.tif', return_np_arrays=True); print(result)"翻译说明:
- 保持代码逻辑不变,仅翻译注释、文档字符串和帮助信息
- 技术术语使用行业标准中文翻译
- 保留英文变量名和函数名以确保代码可读性
- 保留所有版权声明和许可证信息
