鱼C论坛

 找回密码
 立即注册
查看: 2929|回复: 5

怎么将二值化结果“binary”中连续的白色区域提取出来,在原代码基础上更改。

[复制链接]
发表于 2023-8-18 20:01:43 | 显示全部楼层
要提取二值化结果中连续的白色区域,可以使用scipy.ndimage.label函数对二值化图像进行标记,然后使用scipy.ndimage.find_objects函数找到每个连续区域的边界框。

以下是在你的代码基础上添加这些更改的示例:

  1. from tifffile import imread, imwrite
  2. from skimage import filters, color
  3. import numpy as np
  4. from osgeo import gdal
  5. from scipy import ndimage

  6. # 读取TIFF格式无人机影像数据
  7. image_path = r'F:\duneline\dune\dune2.tif'
  8. output_path = 'sobel_222.tif'
  9. image = imread(image_path)

  10. # 转换为灰度图像
  11. gray_image = color.rgb2gray(image)

  12. # 边缘检测,lap取沙丘脊线
  13. edges = filters.laplace(gray_image)

  14. # 计算局部自适应阈值
  15. threshold = filters.threshold_local(edges, block_size=11, offset=0.008)

  16. # 将阈值应用于图像,得到二值化图像
  17. edg = edges < threshold
  18. binary = edg * 255

  19. # 标记连续的白色区域
  20. label_image, num_labels = ndimage.label(binary)

  21. # 找到每个连续区域的边界框
  22. regions = ndimage.find_objects(label_image)

  23. # 创建新的输出图像
  24. driver = gdal.GetDriverByName('GTiff')
  25. out_ds = driver.Create(output_path, image.shape[1], image.shape[0], 1, gdal.GDT_Byte)

  26. # 修改数据类型为gdal.GDT_Byte
  27. out_band = out_ds.GetRasterBand(1)
  28. out_band.WriteArray(label_image.astype(np.uint8))  # 将标记图像写入输出

  29. # 设置颜色表,用于可视化连续区域
  30. color_table = gdal.ColorTable()
  31. for i in range(num_labels):
  32.     color_table.SetColorEntry(i+1, (255, 255, 255))  # 每个连续区域使用白色
  33. out_band.SetColorTable(color_table)

  34. # 设置输出图像的空间参考信息
  35. in_ds = gdal.Open(image_path)
  36. projection = in_ds.GetProjection()
  37. geotransform = in_ds.GetGeoTransform()
  38. out_ds.SetProjection(projection)
  39. out_ds.SetGeoTransform(geotransform)

  40. # 释放资源
  41. out_band.FlushCache()
  42. out_ds = None
  43. in_ds = None

  44. print("保存成功!")
复制代码


在修正后的代码中,我们使用scipy.ndimage.label函数对二值化图像进行标记,并获得标记图像和连续区域的数量。然后,我们使用scipy.ndimage.find_objects函数找到每个连续区域的边界框。最后,我们将标记图像写入输出文件,并为每个连续区域设置白色的颜色表条目。

希望这可以帮助到你!如果还有其他问题,请随时提问。
如果问题已经解决,请设置最佳答案
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-14 03:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表