基于rasterio 给出拼接自定义大小的遥感影像代码,带有overlap,读取图像是以行列号命名
时间: 2024-03-06 14:46:49 浏览: 16
好的,以下是基于rasterio实现拼接遥感影像的代码,支持自定义大小和带有overlap:
```python
import os
import numpy as np
import rasterio
from rasterio.windows import Window
def merge_rasters(file_list, output_path, tile_size=512, overlap=0):
"""
Merge a list of rasters into a single raster with custom tile size and overlap.
Args:
file_list (list): List of raster file paths to merge.
output_path (str): Output file path.
tile_size (int): Size of each tile (default: 512).
overlap (int): Size of overlap between adjacent tiles (default: 0).
"""
if len(file_list) == 0:
raise ValueError("No files found to merge.")
# Open the first file to get metadata
with rasterio.open(file_list[0]) as src0:
meta = src0.meta
# Update metadata with new tile size and overlap
meta.update({
'width': tile_size,
'height': tile_size,
'transform': rasterio.windows.transform(meta['bounds'], tile_size, tile_size),
'count': 1
})
# Calculate the number of tiles needed in each dimension
x_tiles = int(np.ceil(meta['width'] / (tile_size - overlap)))
y_tiles = int(np.ceil(meta['height'] / (tile_size - overlap)))
# Create output file
with rasterio.open(output_path, 'w', **meta) as dst:
for y in range(y_tiles):
for x in range(x_tiles):
# Calculate the window for this tile
window = Window(
x * (tile_size - overlap),
y * (tile_size - overlap),
min(tile_size, meta['width'] - x * (tile_size - overlap)),
min(tile_size, meta['height'] - y * (tile_size - overlap))
)
# Initialize an array to hold the tile data
tile_data = np.zeros((meta['count'], window.height, window.width), dtype=meta['dtype'])
# Read the data from each input file
for file_path in file_list:
with rasterio.open(file_path) as src:
tile = src.read(window=window)
tile_data += tile
# Write the tile to the output file
dst.write(tile_data, window=window)
print(f"Output written to {output_path}")
```
使用示例:
```python
file_list = ['row_col_0_0.tif', 'row_col_0_1.tif', 'row_col_1_0.tif', 'row_col_1_1.tif']
output_path = 'merged.tif'
merge_rasters(file_list, output_path, tile_size=512, overlap=128)
```
其中 `file_list` 是待拼接的遥感影像文件列表,`output_path` 是拼接后的输出文件路径,`tile_size` 是每个小块的大小,`overlap` 是每个小块之间的重叠大小。在上面的示例中,我们将tile_size设置为512,overlap设置为128。