请参考下面的代码,在原代码的基础上添加了提取左侧边界线的功能。from tifffile import imreadimport numpy as npfrom osgeo import gdal# 读取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 = 7 # 窗口大小k = 0.1 # 控制阈值的参数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# 提取左侧边界线boundary = np.zeros_like(binary, dtype=np.uint8)for i in range(binary.shape[0]): for j in range(1, binary.shape[1]): if binary[i, j-1] == 0 and binary[i, j] == 255: # 左侧边界线 boundary[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, image.shape[1], image.shape[0], 1, gdal.GDT_Byte)# 设置输出图像的空间参考信息out_ds.SetProjection(projection)out_ds.SetGeoTransform(geotransform)# 将边界线部分写入输出图像out_band = out_ds.GetRasterBand(1)out_band.WriteArray(boundary.astype(np.uint8))# 设置颜色表color_table = gdal.ColorTable()color_table.SetColorEntry(0, (0, 0, 0, 0)) # 黑色,对应值为0color_table.SetColorEntry(255, (255, 0, 0, 255)) # 红色,对应值为255out_band.SetColorTable(color_table)# 释放资源out_band.FlushCache()out_ds = Nonein_ds = Noneprint("保存成功!")
请尝试运行修改后的代码,看是否能够成功提取结果左侧的边界线并保存图像。
如果回答对你有帮助,请给我一个最佳答案!
|