|
发表于 2023-8-18 20:01:43
|
显示全部楼层
要提取二值化结果中连续的白色区域,可以使用scipy.ndimage.label函数对二值化图像进行标记,然后使用scipy.ndimage.find_objects函数找到每个连续区域的边界框。
以下是在你的代码基础上添加这些更改的示例:
- from tifffile import imread, imwrite
- from skimage import filters, color
- import numpy as np
- from osgeo import gdal
- from scipy import ndimage
- # 读取TIFF格式无人机影像数据
- image_path = r'F:\duneline\dune\dune2.tif'
- output_path = 'sobel_222.tif'
- image = imread(image_path)
- # 转换为灰度图像
- gray_image = color.rgb2gray(image)
- # 边缘检测,lap取沙丘脊线
- edges = filters.laplace(gray_image)
- # 计算局部自适应阈值
- threshold = filters.threshold_local(edges, block_size=11, offset=0.008)
- # 将阈值应用于图像,得到二值化图像
- edg = edges < threshold
- binary = edg * 255
- # 标记连续的白色区域
- label_image, num_labels = ndimage.label(binary)
- # 找到每个连续区域的边界框
- regions = ndimage.find_objects(label_image)
- # 创建新的输出图像
- driver = gdal.GetDriverByName('GTiff')
- out_ds = driver.Create(output_path, image.shape[1], image.shape[0], 1, gdal.GDT_Byte)
- # 修改数据类型为gdal.GDT_Byte
- out_band = out_ds.GetRasterBand(1)
- out_band.WriteArray(label_image.astype(np.uint8)) # 将标记图像写入输出
- # 设置颜色表,用于可视化连续区域
- color_table = gdal.ColorTable()
- for i in range(num_labels):
- color_table.SetColorEntry(i+1, (255, 255, 255)) # 每个连续区域使用白色
- out_band.SetColorTable(color_table)
- # 设置输出图像的空间参考信息
- in_ds = gdal.Open(image_path)
- projection = in_ds.GetProjection()
- geotransform = in_ds.GetGeoTransform()
- out_ds.SetProjection(projection)
- out_ds.SetGeoTransform(geotransform)
- # 释放资源
- out_band.FlushCache()
- out_ds = None
- in_ds = None
- print("保存成功!")
复制代码
在修正后的代码中,我们使用scipy.ndimage.label函数对二值化图像进行标记,并获得标记图像和连续区域的数量。然后,我们使用scipy.ndimage.find_objects函数找到每个连续区域的边界框。最后,我们将标记图像写入输出文件,并为每个连续区域设置白色的颜色表条目。
希望这可以帮助到你!如果还有其他问题,请随时提问。
如果问题已经解决,请设置最佳答案 |
|