Expand_Grid.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. # -*- coding: utf-8 -*-
  2. __author__ = 'wanger'
  3. __description__ = '处理网格数据 遍历要素获取四至坐标点 按照指定距离外扩数据框'
  4. __date__ = '2024-11-25'
  5. __copyright__ = '(C) 2024 by siwei'
  6. __revision__ = '1.0'
  7. import processing
  8. import os
  9. from PyQt5.QtCore import QVariant
  10. from qgis.PyQt.QtCore import QCoreApplication
  11. from qgis._core import QgsSpatialIndex, QgsField, QgsRectangle, QgsProcessingParameterVectorDestination, \
  12. QgsVectorFileWriter, QgsWkbTypes, QgsProcessingParameterNumber, QgsProcessingParameterBoolean, QgsGeometry, \
  13. QgsFeature
  14. from qgis.core import (QgsProcessing,
  15. QgsVectorLayer,
  16. QgsFeatureSink,
  17. QgsProcessingException,
  18. QgsProcessingAlgorithm,
  19. QgsProcessingParameterFile,
  20. QgsProcessingParameterFeatureSource,
  21. QgsProcessingParameterFeatureSink)
  22. from qgis import processing
  23. class ExpandGridProcessingAlgorithm(QgsProcessingAlgorithm):
  24. INPUT = 'INPUT'
  25. OUTPUT = 'OUTPUT'
  26. tolerance = 'tolerance'
  27. expanded = 'expanded'
  28. def tr(self, string):
  29. return QCoreApplication.translate('Processing', string)
  30. def createInstance(self):
  31. return ExpandGridProcessingAlgorithm()
  32. def name(self):
  33. return 'expandGrid'
  34. def displayName(self):
  35. return self.tr('外扩网格数据')
  36. def group(self):
  37. return self.tr('栅格裁剪')
  38. def groupId(self):
  39. return 'rasterclip'
  40. def shortHelpString(self):
  41. return self.tr("遍历输入shp数据要素获取四至坐标点并按照指定距离外扩数据框,保存到输出文件夹。")
  42. def initAlgorithm(self, config=None):
  43. self.addParameter(QgsProcessingParameterFile(
  44. self.INPUT,
  45. '网格数据',
  46. extension='shp'
  47. ))
  48. # 创建一个参数,提示用户输入一个小数值
  49. self.addParameter(QgsProcessingParameterNumber(self.tolerance,
  50. self.tr('外扩距离(米)'),
  51. QgsProcessingParameterNumber.Double
  52. ))
  53. self.addParameter(QgsProcessingParameterBoolean(self.expanded,
  54. self.tr('是否外扩'),
  55. defaultValue=True))
  56. self.addParameter(QgsProcessingParameterVectorDestination(self.OUTPUT,
  57. self.tr('输出位置')))
  58. # 执行
  59. def processAlgorithm(self, parameters, context, feedback):
  60. input_shp = self.parameterAsString(parameters, self.INPUT, context)
  61. output_shp = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
  62. expand_distance = self.parameterAsDouble(parameters, self.tolerance, context)
  63. print(f"expand_distance:{expand_distance}")
  64. expanded = self.parameterAsBoolean(parameters, self.expanded, context)
  65. print(f"expanded:{expanded}")
  66. if expanded == False:
  67. expand_distance = 0
  68. print(f"expanded:{expanded}")
  69. # 加载输入shapefile
  70. input_layer = QgsVectorLayer(input_shp, "input_layer", "ogr")
  71. if not input_layer.isValid():
  72. print(f"Failed to load input shapefile: {input_shp}")
  73. return {
  74. "状态": "处理失败!",
  75. "原因": f"Failed to load input shapefile: {input_shp}"
  76. }
  77. else:
  78. # 获取输入图层的字段信息
  79. fields = input_layer.fields()
  80. # 创建输出shapefile
  81. writer = QgsVectorFileWriter(output_shp, 'UTF-8', fields, QgsWkbTypes.MultiPolygon, input_layer.crs(),
  82. 'ESRI Shapefile')
  83. # 检查文件是否成功创建
  84. if writer.hasError() != QgsVectorFileWriter.NoError:
  85. print(f"Error creating output shapefile: {output_shp}")
  86. return {
  87. "状态": "处理失败!",
  88. "原因": f"Error creating output shapefile: {output_shp}"
  89. }
  90. else:
  91. # 遍历输入shapefile中的要素
  92. for feature in input_layer.getFeatures():
  93. # 获取要素的geometry和extent
  94. geometry = feature.geometry()
  95. extent = geometry.boundingBox() # 获取要素的extent(bounding box)
  96. # 对extent进行外扩
  97. # 使用 grow 方法来将bounding box外扩100米
  98. # if expanded == False:
  99. # extent.grow(expand_distance) # 扩展100米
  100. # print(f"Feature ID: {feature.id()}, Extent: {extent}")
  101. # 获取四至坐标
  102. minX = extent.xMinimum()
  103. maxX = extent.xMaximum()
  104. minY = extent.yMinimum()
  105. maxY = extent.yMaximum()
  106. # 手动扩展extent,向四个方向扩展100米
  107. expanded_minX = minX - expand_distance # 向左扩展
  108. expanded_maxX = maxX + expand_distance # 向右扩展
  109. expanded_minY = minY - expand_distance # 向下扩展
  110. expanded_maxY = maxY + expand_distance # 向上扩展
  111. # 创建新的扩展后的QgsRectangle
  112. expanded_extent = QgsRectangle(expanded_minX, expanded_minY, expanded_maxX, expanded_maxY)
  113. # 使用extent创建一个新的几何(矩形geometry)
  114. new_geometry = QgsGeometry.fromRect(expanded_extent)
  115. # 创建一个新的要素,并将新几何设置到要素中
  116. new_feature = QgsFeature(fields) # 创建新的空要素,使用相同的字段定义
  117. new_feature.setGeometry(new_geometry) # 设置新的几何(extent)
  118. # 复制原始要素的属性到新的要素
  119. new_feature.setAttributes(feature.attributes()) # 将原要素的属性复制到新要素
  120. # 将修改后的要素添加到输出shapefile
  121. writer.addFeature(new_feature)
  122. # 完成写入并关闭输出文件
  123. del writer
  124. print(f"Features copied from {input_shp} to {output_shp} with modified extent.")
  125. return {
  126. "状态": "处理成功"
  127. }