rasterio
是一个用于处理地理空间栅格数据的Python库。提供了一个简单而强大的接口,用于读取、写入和操作栅格数据(如GeoTIFF、NetCDF等)。rasterio
基于GDAL(Geospatial Data Abstraction Library)构建,因此继承了GDAL的强大功能,同时提供了更Pythonic的API。
可以使用pip
来安装rasterio
:
pip install rasterio
使用rasterio
读取栅格数据非常简单。可以使用rasterio.open()
函数打开一个栅格文件,并使用read()
方法读取数据。
import rasterio
# 打开栅格文件
with rasterio.open('example.tif') as src:
# 读取第一个波段的数据
band1 = src.read(1)
# 获取栅格的元数据
meta = src.meta
print(meta)
可以使用rasterio
将数据写入新的栅格文件。首先,需要创建一个新的栅格文件,然后使用write()
方法写入数据。
import numpy as np
import rasterio
from rasterio.transform import from_origin
# 创建一个示例数据
data = np.random.randint(0, 255, (100, 100), dtype=np.uint8)
# 定义元数据
meta = {
'driver': 'GTiff',
'height': data.shape[0],
'width': data.shape[1],
'count': 1,
'dtype': data.dtype,
'crs': 'EPSG:4326', # 坐标参考系统
'transform': from_origin(0, 0, 1, 1) # 变换矩阵
}
# 创建并写入栅格文件
with rasterio.open('output.tif', 'w', **meta) as dst:
dst.write(data, 1)
rasterio
提供了丰富的元数据信息,包括坐标参考系统(CRS)、变换矩阵、波段数量等。
with rasterio.open('example.tif') as src:
print("CRS:", src.crs)
print("Transform:", src.transform)
print("Width:", src.width)
print("Height:", src.height)
print("Number of bands:", src.count)
rasterio
支持多种栅格数据的变换操作,如重采样、裁剪、镶嵌等。
import rasterio
from rasterio.warp import reproject, Resampling
# 打开源栅格文件
with rasterio.open('source.tif') as src:
# 创建目标栅格文件的元数据
dst_meta = src.meta.copy()
dst_meta.update({
'width': 200,
'height': 200,
'transform': from_origin(0, 0, 0.5, 0.5)
})
# 创建目标栅格文件
with rasterio.open('destination.tif', 'w', **dst_meta) as dst:
# 重采样
for i in range(1, src.count + 1):
reproject(
source=rasterio.band(src, i),
destination=rasterio.band(dst, i),
src_transform=src.transform,
src_crs=src.crs,
dst_transform=dst_meta['transform'],
dst_crs=dst_meta['crs'],
resampling=Resampling.bilinear
)
可以使用rasterio
裁剪栅格数据,通常使用rasterio.mask.mask()
函数。
import rasterio
from rasterio.mask import mask
from shapely.geometry import box
import geopandas as gpd
# 打开栅格文件
with rasterio.open('example.tif') as src:
# 定义裁剪区域
bbox = box(0, 0, 100, 100)
geo = gpd.GeoDataFrame({'geometry': bbox}, index=[0], crs=src.crs)
coords = [feature["geometry"] for feature in geo.to_crs(src.crs).to_dict('records')]
# 裁剪栅格数据
out_image, out_transform = mask(src, shapes=coords, crop=True)
out_meta = src.meta.copy()
out_meta.update({
'height': out_image.shape[1],
'width': out_image.shape[2],
'transform': out_transform
})
# 保存裁剪后的栅格数据
with rasterio.open('cropped.tif', 'w', **out_meta) as dst:
dst.write(out_image)
可以使用read()
方法读取多个波段的数据。
with rasterio.open('example.tif') as src:
bands = src.read() # 读取所有波段
print(bands.shape) # (波段数, 高度, 宽度)
可以使用rasterio.plot
模块来获取栅格数据的统计信息,如直方图。
import rasterio
import rasterio.plot as rioplot
import matplotlib.pyplot as plt
with rasterio.open('example.tif') as src:
band1 = src.read(1)
rioplot.show(band1)
plt.show()
rasterio
是一个功能强大的库,适用于处理各种地理空间栅格数据。提供了简单易用的API,使得读取、写入、变换和分析栅格数据变得非常方便。无论是处理遥感影像、地形数据还是其他类型的栅格数据,rasterio
都是一个不可或缺的工具。