from tifffile import imread
import numpy as np
from osgeo import gdal, osr
# 读取TIFF格式无人机影像数据
image_path = 'F:\duneline\dune\dune.tif'
output_path = 'overlay_image.tif'
image = imread(image_path)
# 将输入图像转换为灰度图像
gray_image = np.mean(image, axis=2)
# 自适应阈值二值化
binary = np.zeros_like(gray_image, dtype=np.uint8)
window_size = 131 # 窗口大小
k = 0.3 # 控制阈值的参数
for i in range(window_size//2, gray_image.shape[0]-window_size//2):
for j in range(window_size//2, gray_image.shape[1]-window_size//2):
window = gray_image[i-window_size//2:i+window_size//2+1, j-window_size//2:j+window_size//2+1]
threshold = np.mean(window) - k * np.std(window)
if gray_image[i, j] > threshold:
binary[i, j] = 255
# 配置输出的空间参考信息
in_ds = gdal.Open(image_path)
projection = in_ds.GetProjection()
geotransform = in_ds.GetGeoTransform()
# 创建新的输出图像
driver = gdal.GetDriverByName('GTiff')
out_ds = driver.Create(output_path, binary.shape[1], binary.shape[0], 1, gdal.GDT_Byte,
options=['COMPRESS=NONE']) # 修改数据类型为gdal.GDT_Byte且关闭压缩
# 设置输出图像的空间参考信息
out_ds.SetProjection(projection)
out_ds.SetGeoTransform(geotransform)
# 将沙脊线部分写入输出图像
out_band = out_ds.GetRasterBand(1)
out_band.WriteArray(binary) # 直接写入binary数组
# 设置颜色表
color_table = gdal.ColorTable()
for i in range(256): # 对所有可能的像素值进行映射
if i == 0:
color_table.SetColorEntry(i, (0, 0, 0, 255)) # 黑色,对应值为0
elif i == 255:
color_table.SetColorEntry(i, (255, 255, 255, 255)) # 白色,对应值为255
else:
color_table.SetColorEntry(i, (i, i, i, 255)) # 将其他的值映射为相应的灰度色
out_band.SetColorTable(color_table)
# 释放资源
out_band.FlushCache()
out_ds = None
in_ds = None
print("保存成功!")
|