均值滤波处理Geotiff影像
时间: 2025-01-03 18:30:47 浏览: 4
### 使用均值滤波处理 Geotiff 影像
对于 Geotiff 影像的均值滤波处理,可以利用 `GDAL` 进行影像读取和写入操作,并借助 `OpenCV` 实现均值滤波功能。下面展示一段 Python 代码来完成这一过程。
#### 安装依赖库
确保安装了必要的 Python 库:
```bash
pip install numpy opencv-python gdal
```
#### 均值滤波处理代码实现
```python
import cv2
from osgeo import gdal, ogr, osr
import numpy as np
def read_geotiff(file_path):
dataset = gdal.Open(file_path)
cols = dataset.RasterXSize
rows = dataset.RasterYSize
bands_num = dataset.RasterCount
geotransform = dataset.GetGeoTransform()
projection = dataset.GetProjection()
band_data = []
for i in range(bands_num):
band = dataset.GetRasterBand(i + 1).ReadAsArray(0, 0, cols, rows)
band_data.append(band)
return np.array(band_data), geotransform, projection
def write_geotiff(filename, array, geotransform, projection):
driver = gdal.GetDriverByName('GTiff')
outdata = driver.Create(filename, array.shape[2], array.shape[1], array.shape[0], gdal.GDT_UInt16)
for i in range(array.shape[0]):
outband = outdata.GetRasterBand(i + 1)
outband.WriteArray(array[i])
outdata.SetGeoTransform(geotransform)
outdata.SetProjection(projection)
outdata.FlushCache() # Write to disk.
input_file = 'path_to_input.tif'
output_file = 'path_to_output_filtered.tif'
# Read GeoTIFF file and get its metadata
image_array, geo_transform, proj_info = read_geotiff(input_file)[^1]
filtered_bands = []
for single_band in image_array:
filtered_image = cv2.blur(single_band,(5,5)) # Apply mean filter with kernel size of 5x5
filtered_bands.append(filtered_image)
write_geotiff(output_file, np.array(filtered_bands), geo_transform, proj_info)
```
此段程序首先定义两个辅助函数用于读取与保存 Geotiff 文件;接着通过调用 OpenCV 的 blur 函数对每一波段应用均值滤波器,最后将处理后的数据重新组合并存储回新的 Geotiff 文件中。
阅读全文