Browse Source

遥感技术部需求脚本提交

wanger 7 months ago
parent
commit
beb08f9fb5

+ 16 - 5
processing/tools/PostgreSQL/PgExxcute.py

@@ -1,8 +1,19 @@
 # -*- coding: utf-8 -*-
-from PostgreSQL import PostgreSQL
+# from PostgreSQL import PostgreSQL
 
+import sys
+
+print(sys.getdefaultencoding())
+
+import os
+
+# 获取PYTHONIOENCODING的值
+python_io_encoding = os.getenv('PYTHONIOENCODING')
+
+# 打印结果
+print(f"PYTHONIOENCODING: {python_io_encoding}")
 # pgconn = PostgreSQL(schema='gis')
-pgconn = PostgreSQL()
-rows = pgconn.execute(sql="SELECT 省,类型 from \"XZQH3857\"")
-print(rows)
-pgconn.close()
+# pgconn = PostgreSQL()
+# rows = pgconn.execute(sql="SELECT 省,类型 from \"XZQH3857\"")
+# print(rows)
+# pgconn.close()

+ 4 - 86
processing/tools/Raster/ClipRasterByGrid.py

@@ -6,35 +6,17 @@ __date__ = '2024-11-25'
 __copyright__ = '(C) 2024 by siwei'
 __revision__ = '1.0'
 
-import os
 import subprocess
 
-import math
-
-from qgis._core import QgsRasterFileWriter, QgsProcessingParameterFolderDestination
+from qgis._core import QgsProcessingParameterFolderDestination
 from qgis.core import (
-    QgsVectorLayer,
     QgsRasterLayer,
-    QgsFeature,
-    QgsGeometry
 )
-import processing
-from PyQt5.QtCore import QFileInfo
-from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
 
 from qgis.PyQt.QtCore import QCoreApplication
-from qgis._core import QgsSpatialIndex, QgsField, QgsRectangle, QgsProcessingParameterVectorDestination, \
-    QgsVectorFileWriter, QgsWkbTypes, QgsProcessingParameterNumber, QgsProcessingParameterBoolean, QgsGeometry, \
-    QgsFeature
-from qgis.core import (QgsProcessing,
-                       QgsVectorLayer,
-                       QgsFeatureSink,
-                       QgsProcessingException,
+from qgis.core import (QgsVectorLayer,
                        QgsProcessingAlgorithm,
-                       QgsProcessingParameterFile,
-                       QgsProcessingParameterFeatureSource,
-                       QgsProcessingParameterFeatureSink)
-from qgis import processing
+                       QgsProcessingParameterFile)
 
 
 class ClipRasterByMaskProcessingAlgorithm(QgsProcessingAlgorithm):
@@ -52,7 +34,7 @@ class ClipRasterByMaskProcessingAlgorithm(QgsProcessingAlgorithm):
         return 'cliprasterbymask'
 
     def displayName(self):
-        return self.tr('按照掩膜范围裁剪栅格数据')
+        return self.tr('栅格裁剪')
 
     def group(self):
         return self.tr('栅格裁剪')
@@ -74,8 +56,6 @@ class ClipRasterByMaskProcessingAlgorithm(QgsProcessingAlgorithm):
             '栅格数据',
             extension='tif'
         ))
-        # 通过 setExtensions 方法设置多个扩展名
-        # self.parameter(self.INPUT_RASTER).setExtensions(['tif', 'img'])  # 支持 .shp, .csv, .txt
         self.addParameter(QgsProcessingParameterFolderDestination(self.OUTPUT, '输出文件夹'))
 
     # 执行
@@ -83,12 +63,6 @@ class ClipRasterByMaskProcessingAlgorithm(QgsProcessingAlgorithm):
         input_shp = self.parameterAsString(parameters, self.INPUT_SHP, context)
         input_raster = self.parameterAsOutputLayer(parameters, self.INPUT_RASTER, context)
         output_raster = self.parameterAsString(parameters, self.OUTPUT, context)
-        # 输入Shapefile路径
-        # input_shp = "E:\\projects\\遥感技术部需求\\裁剪栅格\\data\\grid_extent.shp"
-        # 输入栅格数据路径
-        # input_raster = "D:\\gisdata\\tif\\unnamed_卫图_Level_12.tif"
-        # 输出裁剪后的栅格路径
-        # output_raster = "E:\\projects\\遥感技术部需求\\裁剪栅格\\output\\"
         # 加载输入Shapefile和栅格数据
         vector_layer = QgsVectorLayer(input_shp, "vector_layer", "ogr")
         raster_layer = QgsRasterLayer(input_raster, "raster_layer")
@@ -103,53 +77,16 @@ class ClipRasterByMaskProcessingAlgorithm(QgsProcessingAlgorithm):
             geometry = feature.geometry()
             key = feature["新图号"]
             extent = geometry.boundingBox()
-
-            # 创建一个新的 Shapefile 文件名,可以使用索引或 ID 来命名
-            # output_shp = os.path.join(output_raster, f"{key}.shp")
-            #
-            # # 创建输出shapefile
-            # writer = QgsVectorFileWriter(output_shp, 'UTF-8', fields, QgsWkbTypes.MultiPolygon, vector_layer.crs(),
-            #                              'ESRI Shapefile')
-            # writer.addFeature(feature)
-            #
-            # # 完成写入并关闭输出文件
-            # del writer
-
-            # 使用QGIS的processing模块进行栅格裁剪
-            # params = {
-            #     'INPUT': raster_layer,  # 输入栅格
-            #     'MASK': output_shp,  # 用于裁剪的矢量图层
-            #     'OUTPUT': f"{output_raster}\\{key}.tif",  # 输出裁剪后的栅格文件
-            #     'CROP_TO_CUTLINE': True
-            # }
-            # 调用 clipRasterByExtent 进行裁剪
-            # vector_layer_cur = QgsVectorLayer(output_shp, 'Shapefile Layer')
-            # params = {
-            #     'INPUT': input_raster,
-            #     'EXTENT': vector_layer_cur.extent(),
-            #     'PROJWIN': vector_layer_cur.extent(),
-            #     'OUTPUT': f"{output_raster}\\{key}.tif"
-            # }
-            # extent = vector_layer_cur.extent()
             # 计算裁剪范围的整数倍,确保裁剪范围对齐
             minX = extent.xMinimum()
             maxX = extent.xMaximum()
             minY = extent.yMinimum()
             maxY = extent.yMaximum()
-
             # 通过对齐最大值,确保裁剪范围完整
             maxX_aligned = maxX + pixel_width
             maxY_aligned = maxY + pixel_width
             minX_aligned = minX - pixel_width
             minY_aligned = minY - pixel_width
-            # maxX_aligned = math.ceil(maxX / pixel_width) * pixel_width + pixel_width
-            # maxY_aligned = math.ceil(maxY / pixel_height) * pixel_height + pixel_width
-            # minX_aligned = math.floor(minX / pixel_width) * pixel_width - pixel_width
-            # minY_aligned = math.floor(minY / pixel_height) * pixel_height - pixel_width
-            # extent_cur = f'{minX},{extent.yMaximum()},{extent.xMaximum()},{minY}'  # 裁剪范围:minX,maxY,maxX,minY
-            # extent_cur = f'524101.737 3310956.7264999966 530229.7547000019 3306243.2199'  # 裁剪范围:minX,maxY,maxX,minY
-            # print(extent_cur)
-
             # 设置 gdal_translate 命令和参数
             gdal_translate_cmd = [
                 'gdal_translate',  # GDAL 工具名称
@@ -160,7 +97,6 @@ class ClipRasterByMaskProcessingAlgorithm(QgsProcessingAlgorithm):
                 f"{output_raster}\\{key}.tif"  # 输出文件路径
             ]
             print(gdal_translate_cmd)
-
             # 运行命令
             try:
                 subprocess.run(gdal_translate_cmd, check=True)
@@ -168,24 +104,6 @@ class ClipRasterByMaskProcessingAlgorithm(QgsProcessingAlgorithm):
                 total = total + 1
             except subprocess.CalledProcessError as e:
                 print(f"gdal_translate 执行失败: {e}")
-
-            # 3. 调用 `gdal:translate` 进行裁剪
-            # parameters = {
-            #     'INPUT': input_raster,  # 输入栅格
-            #     'OUTPUT': f"{output_raster}\\{key}.tif",  # 输出路径
-            #     'PROJWIN': extent_cur,  # 裁剪范围 (左下右上)
-            #     # 'TARGET_CRS': 'EPSG:4544'  # 可选:指定目标坐标系统(如果需要)
-            # }
-            # print(parameters)
-
-            # 4. 运行工具
-            # processing.run('gdal:translate', parameters)
-
-            # 执行裁剪操作
-            # processing.run('gdal:cliprasterbyextent', params)
-            # processing.run('gdal:cliprasterbymasklayer', params)
-            # print(f"Cropped raster saved to {output_raster}")
-
         return {
             "状态": f"处理成功,共裁剪出{total}块栅格数据。"
         }

+ 32 - 30
processing/tools/Raster/Expand_Grid.py

@@ -5,24 +5,15 @@ __description__ = '处理网格数据  遍历要素获取四至坐标点  按照
 __date__ = '2024-11-25'
 __copyright__ = '(C) 2024 by siwei'
 __revision__ = '1.0'
-import processing
-import os
 
-from PyQt5.QtCore import QVariant
 
 from qgis.PyQt.QtCore import QCoreApplication
-from qgis._core import QgsSpatialIndex, QgsField, QgsRectangle, QgsProcessingParameterVectorDestination, \
+from qgis._core import QgsRectangle, QgsProcessingParameterVectorDestination, \
     QgsVectorFileWriter, QgsWkbTypes, QgsProcessingParameterNumber, QgsProcessingParameterBoolean, QgsGeometry, \
     QgsFeature
-from qgis.core import (QgsProcessing,
-                       QgsVectorLayer,
-                       QgsFeatureSink,
-                       QgsProcessingException,
+from qgis.core import (QgsVectorLayer,
                        QgsProcessingAlgorithm,
-                       QgsProcessingParameterFile,
-                       QgsProcessingParameterFeatureSource,
-                       QgsProcessingParameterFeatureSink)
-from qgis import processing
+                       QgsProcessingParameterFile)
 
 
 class ExpandGridProcessingAlgorithm(QgsProcessingAlgorithm):
@@ -30,6 +21,7 @@ class ExpandGridProcessingAlgorithm(QgsProcessingAlgorithm):
     OUTPUT = 'OUTPUT'
     tolerance = 'tolerance'
     expanded = 'expanded'
+    resolution = 'resolution'
 
     def tr(self, string):
         return QCoreApplication.translate('Processing', string)
@@ -41,7 +33,7 @@ class ExpandGridProcessingAlgorithm(QgsProcessingAlgorithm):
         return 'expandGrid'
 
     def displayName(self):
-        return self.tr('外扩网格数据')
+        return self.tr('网格数据外扩')
 
     def group(self):
         return self.tr('栅格裁剪')
@@ -58,6 +50,11 @@ class ExpandGridProcessingAlgorithm(QgsProcessingAlgorithm):
             '网格数据',
             extension='shp'
         ))
+        # 栅格分辨率
+        self.addParameter(QgsProcessingParameterNumber(self.resolution,
+                                                       self.tr('栅格分辨率'),
+                                                       QgsProcessingParameterNumber.Double
+                                                       ))
         # 创建一个参数,提示用户输入一个小数值
         self.addParameter(QgsProcessingParameterNumber(self.tolerance,
                                                        self.tr('外扩距离(米)'),
@@ -74,6 +71,7 @@ class ExpandGridProcessingAlgorithm(QgsProcessingAlgorithm):
         input_shp = self.parameterAsString(parameters, self.INPUT, context)
         output_shp = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
         expand_distance = self.parameterAsDouble(parameters, self.tolerance, context)
+        resolution = self.parameterAsDouble(parameters, self.resolution, context)
         print(f"expand_distance:{expand_distance}")
         expanded = self.parameterAsBoolean(parameters, self.expanded, context)
         print(f"expanded:{expanded}")
@@ -107,23 +105,27 @@ class ExpandGridProcessingAlgorithm(QgsProcessingAlgorithm):
                     # 获取要素的geometry和extent
                     geometry = feature.geometry()
                     extent = geometry.boundingBox()  # 获取要素的extent(bounding box)
-                    # 对extent进行外扩
-                    # 使用 grow 方法来将bounding box外扩100米
-                    # if expanded == False:
-                    #     extent.grow(expand_distance)  # 扩展100米
-                    # print(f"Feature ID: {feature.id()}, Extent: {extent}")
-                    # 获取四至坐标
-                    minX = extent.xMinimum()
-                    maxX = extent.xMaximum()
-                    minY = extent.yMinimum()
-                    maxY = extent.yMaximum()
-                    # 手动扩展extent,向四个方向扩展100米
-                    expanded_minX = minX - expand_distance  # 向左扩展
-                    expanded_maxX = maxX + expand_distance  # 向右扩展
-                    expanded_minY = minY - expand_distance  # 向下扩展
-                    expanded_maxY = maxY + expand_distance  # 向上扩展
-                    # 创建新的扩展后的QgsRectangle
-                    expanded_extent = QgsRectangle(expanded_minX, expanded_minY, expanded_maxX, expanded_maxY)
+                    # TODO 创建新的扩展后的QgsRectangle
+                    rings = None
+                    try:
+                        rings = geometry.asPolygon()
+                    except Exception as e:
+                        rings = geometry.asMultiPolygon()
+                        rings = rings[0]
+                    finally:
+                        print("读取完成")
+                    print("开始计算")
+                    ring = rings[0]
+                    p1 = ring[0]
+                    p2 = ring[1]
+                    p3 = ring[2]
+                    p4 = ring[3]
+                    ymax = int((max(p1.y(), p2.y(), p3.y(), p4.y()) + expand_distance) / resolution) * resolution
+                    xmin = int((min(p1.x(), p2.x(), p3.x(), p4.x()) - expand_distance) / resolution) * resolution
+                    ymin = int((min(p1.y(), p2.y(), p3.y(), p4.y()) - expand_distance) / resolution) * resolution
+                    xmax = int((max(p1.x(), p2.x(), p3.x(), p4.x()) + expand_distance) / resolution) * resolution
+                    print(f"{xmin},{ymin},{xmax},{ymax}")
+                    expanded_extent = QgsRectangle(xmin, ymin, xmax, ymax)
                     # 使用extent创建一个新的几何(矩形geometry)
                     new_geometry = QgsGeometry.fromRect(expanded_extent)
                     # 创建一个新的要素,并将新几何设置到要素中

+ 4 - 10
processing/tools/Raster/FishNet.py

@@ -12,15 +12,9 @@ from PyQt5.QtCore import QVariant
 
 from qgis.PyQt.QtCore import QCoreApplication
 from qgis._core import QgsSpatialIndex, QgsField, QgsRectangle
-from qgis.core import (QgsProcessing,
-                       QgsVectorLayer,
-                       QgsFeatureSink,
-                       QgsProcessingException,
+from qgis.core import (QgsVectorLayer,
                        QgsProcessingAlgorithm,
-                       QgsProcessingParameterFile,
-                       QgsProcessingParameterFeatureSource,
-                       QgsProcessingParameterFeatureSink)
-from qgis import processing
+                       QgsProcessingParameterFile)
 
 
 class FishNetProcessingAlgorithm(QgsProcessingAlgorithm):
@@ -36,10 +30,10 @@ class FishNetProcessingAlgorithm(QgsProcessingAlgorithm):
         return 'makeFishNet'
 
     def displayName(self):
-        return self.tr('处理网格数据')
+        return self.tr('网格数据预处理')
 
     def group(self):
-        return self.tr('栅格数据')
+        return self.tr('栅格数据生成')
 
     def groupId(self):
         return 'metadata'

+ 10 - 19
processing/tools/Raster/makeMetadate.py

@@ -11,26 +11,18 @@ from osgeo import gdal, osr
 import openpyxl
 from qgis.core import (
     QgsRasterLayer,
-    QgsVectorLayer,
     QgsSpatialIndex,
-    QgsFeatureRequest,
     QgsGeometry
 )
 from qgis.PyQt.QtCore import NULL
 from qgis.PyQt.QtCore import QCoreApplication
-from qgis.core import (QgsProcessing,
-                       QgsFeatureSink,
-                       QgsExpression,
+from qgis.core import (QgsExpression,
                        QgsFeatureRequest,
                        QgsVectorLayer,
-                       QgsProcessingException,
                        QgsProcessingAlgorithm,
-                       QgsProcessingParameterFeatureSource,
                        QgsProcessingParameterFolderDestination,
                        QgsProcessingParameterString,
-                       QgsProcessingParameterFile,
-                       QgsProcessingParameterFeatureSink)
-from qgis import processing
+                       QgsProcessingParameterFile)
 
 
 class MakeMetadataProcessingAlgorithm(QgsProcessingAlgorithm):
@@ -54,7 +46,7 @@ class MakeMetadataProcessingAlgorithm(QgsProcessingAlgorithm):
         return self.tr('生成栅格元数据')
 
     def group(self):
-        return self.tr('栅格数据')
+        return self.tr('栅格数据生成')
 
     def groupId(self):
         return 'metadata'
@@ -181,10 +173,6 @@ class MakeMetadataProcessingAlgorithm(QgsProcessingAlgorithm):
         west = f"{self.replacestr(string=image_number, oldvalue=str(imagey).zfill(length), newvalue=str(imagey - 1).zfill(length), type='last')}.{image_format}"
         north = f"{self.replacestr(string=image_number, oldvalue=str(imagex).zfill(length), newvalue=str(imagex - 1).zfill(length), type='first')}.{image_format}"
         south = f"{self.replacestr(string=image_number, oldvalue=str(imagex).zfill(length), newvalue=str(imagex + 1).zfill(length), type='first')}.{image_format}"
-        # print(selectfeature["east"])
-        # print(selectfeature["west"])
-        # print(selectfeature["north"])
-        # print(selectfeature["south"])
         return {
             "east": selectfeature["east"] if selectfeature["east"] != NULL else self.hasFile(east, folder_path),
             "west": selectfeature["west"] if selectfeature["west"] != NULL else self.hasFile(west, folder_path),
@@ -285,7 +273,7 @@ class MakeMetadataProcessingAlgorithm(QgsProcessingAlgorithm):
                     decimal_number = None
                     for band_index in range(1, dataset.RasterCount + 1):
                         band = dataset.GetRasterBand(band_index)
-                        nodata_list.append(band.GetNoDataValue())
+                        nodata_list.append(int(band.GetNoDataValue()))
                         stats = band.GetStatistics(True, True)  # 获取统计信息
                         min_value, max_value = stats[0], stats[1]
                         if min_value is not None and max_value is not None:
@@ -301,7 +289,6 @@ class MakeMetadataProcessingAlgorithm(QgsProcessingAlgorithm):
                     x_resolution = abs(geo_transform[1])  # 像素宽度
                     y_resolution = abs(geo_transform[5])  # 像素高度
                     grid_size = f"{self.processingNumericalValues(x_resolution)}*{self.processingNumericalValues(y_resolution)}"
-                    # grid_size = f"{x_resolution}*{y_resolution}"
                     # 获取投影信息
                     projection = dataset.GetProjection()
                     # 获取栅格数据的投影信息
@@ -391,7 +378,11 @@ class MakeMetadataProcessingAlgorithm(QgsProcessingAlgorithm):
                     value = overlapParams[key]
                     largest_feature = self.get_largest_overlapping_feature(raster_path=filepath,
                                                                            shp_path=overlapVectorPath)
-                    field_value = largest_feature[value]
+                    if key == "data_gain_date":
+                        data_gain_date = largest_feature[value]
+                        field_value = f"{data_gain_date[0:4]}/{data_gain_date[4:6]}/{data_gain_date[6:8]}"
+                    else:
+                        field_value = largest_feature[value]
                     metadatadict[key] = field_value
                 print(f"开始生成元数据:{image_number}")
                 # 利用模板生成excel
@@ -415,7 +406,7 @@ class MakeMetadataProcessingAlgorithm(QgsProcessingAlgorithm):
                                     except Exception as e:
                                         print(e)
                 # 保存修改后的文件
-                workbook.save(f'{output_path}\\{image_number}.xlsx')
+                workbook.save(f'{output_path}\\{image_number}.xls')
                 totalNumber = totalNumber + 1
                 print(f"元数据生成完成:{image_number}")
         print(f"共生成{totalNumber}个元数据表。")

+ 56 - 139
processing/tools/Raster/test.py

@@ -1,140 +1,57 @@
-from PyQt5.QtCore import QVariant
-
-from qgis.core import *
-from qgis.utils import iface
-from qgis.core import QgsExpression, QgsFeatureRequest, QgsVectorLayer
-
-# 获取渔网图层(假设图层已经加载)
-shp_path = "E:\\projects\\遥感技术部需求\\批量生成元数据\\make\\template\\allfishnet.shp"
-layer = QgsVectorLayer(shp_path, "Fish Layer", "ogr")
-
-# 获取网格宽度和高度(假设是规则网格)
-extent = layer.extent()
-
-grid_width = 100  # 替换为实际网格宽度
-grid_height = 100  # 替换为实际网格高度
-
-# 确保图层有至少一个要素
-if layer.featureCount() > 0:
-    # 获取第一个要素
-    feature = next(layer.getFeatures())
-    geom = feature.geometry()
-    # 获取要素的边界矩形(bounding box)
-    bounds = geom.boundingBox()
-    # 计算宽度和高度
-    grid_width = bounds.width()
-    grid_height = bounds.height()
-    print(f"网格宽度:{grid_width}")
-    print(f"网格高度:{grid_height}")
+from qgis._core import QgsWkbTypes
+from qgis.core import QgsVectorLayer, QgsFeature
+
+# 加载Shapefile
+layer = QgsVectorLayer("E:\\projects\\遥感技术部需求\\裁剪栅格\\data\\grid.shp", "grid", "ogr")
+D = 40
+d = 2
+# 检查图层是否加载成功
+if not layer.isValid():
+    print("图层加载失败!")
 else:
-    print("图层没有任何要素!")
-
-# 为图层添加邻居字段
-layer.startEditing()
-for field in ["east", "west", "south", "north"]:
-    if field not in [f.name() for f in layer.fields()]:
-        layer.dataProvider().addAttributes([QgsField(field, QVariant.String)])
-layer.updateFields()
-# 创建空间索引
-spatial_index = QgsSpatialIndex(layer)
-# 设置误差值 过滤掉仅仅是边线重叠的数据
-miss = 0.04
-def cacl(neighbors):
-    if len(neighbors) == 0:
-        return "自由"
-    else:
-        return None
-
-# 遍历图层中的所有要素
-for feature in layer.getFeatures():
-    geom = feature.geometry()
-    extent = geom.boundingBox()
-
-    # 获取网格宽度和高度
-    width = grid_width
-    height = grid_height
-
-    # 构造东西南北方向的矩形
-    west_extent = QgsRectangle(extent.xMinimum() - width + miss, extent.yMinimum() + miss, extent.xMinimum() - miss,
-                               extent.yMaximum() - miss)
-    east_extent = QgsRectangle(extent.xMaximum() + miss, extent.yMinimum() + miss, extent.xMaximum() + width - miss,
-                               extent.yMaximum() - miss)
-    south_extent = QgsRectangle(extent.xMinimum() + miss, extent.yMinimum() - height + miss, extent.xMaximum() - miss,
-                                extent.yMinimum() - miss)
-    north_extent = QgsRectangle(extent.xMinimum() + miss, extent.yMaximum() + miss, extent.xMaximum() - miss,
-                                extent.yMaximum() + height - miss)
-
-    # 查询每个方向是否有其他网格
-    west_neighbors = spatial_index.intersects(west_extent)
-    east_neighbors = spatial_index.intersects(east_extent)
-    south_neighbors = spatial_index.intersects(south_extent)
-    north_neighbors = spatial_index.intersects(north_extent)
-
-    neighbor_geometries = {
-        "north": cacl(north_neighbors),
-        "south": cacl(south_neighbors),
-        "west": cacl(west_neighbors),
-        "east": cacl(east_neighbors)
-    }
-    for direction, value in neighbor_geometries.items():
-        feature[direction] = value
-    layer.updateFeature(feature)
-# 保存编辑
-layer.commitChanges()
-
-# 批量处理每个网格
-# for feature in layer.getFeatures():
-#     geom = feature.geometry()
-#     rectangle = geom.boundingBox()
-#     centroid = geom.centroid().asPoint()
-#     # 定义邻居的目标几何
-#     neighbor_geometries = {
-#         "north": QgsRectangle(
-#             rectangle.xMinimum() + 0,
-#             rectangle.yMinimum() + grid_height,
-#             rectangle.xMaximum() + 0,
-#             rectangle.yMaximum() + grid_height
-#         ),
-#         "south": QgsRectangle(centroid.x() - grid_width / 2, centroid.y() - 1.5 * grid_height,
-#                               centroid.x() + grid_width / 2, centroid.y() - grid_height / 2),
-#         "west": QgsRectangle(centroid.x() - 1.5 * grid_width, centroid.y() - grid_height / 2,
-#                              centroid.x() - grid_width / 2, centroid.y() + grid_height / 2),
-#         "east": QgsRectangle(centroid.x() + grid_width / 2, centroid.y() - grid_height / 2,
-#                              centroid.x() + 1.5 * grid_width, centroid.y() + grid_height / 2)
-#     }
-#     # neighbor_geometries = {
-#     #     "north": QgsRectangle(centroid.x() - grid_width / 2, centroid.y() + grid_height / 2,
-#     #                           centroid.x() + grid_width / 2, centroid.y() + 1.5 * grid_height),
-#     #     "south": QgsRectangle(centroid.x() - grid_width / 2, centroid.y() - 1.5 * grid_height,
-#     #                           centroid.x() + grid_width / 2, centroid.y() - grid_height / 2),
-#     #     "west": QgsRectangle(centroid.x() - 1.5 * grid_width, centroid.y() - grid_height / 2,
-#     #                          centroid.x() - grid_width / 2, centroid.y() + grid_height / 2),
-#     #     "east": QgsRectangle(centroid.x() + grid_width / 2, centroid.y() - grid_height / 2,
-#     #                          centroid.x() + 1.5 * grid_width, centroid.y() + grid_height / 2)
-#     # }
-#     # neighbor_geometries = {
-#     #     "north": QgsRectangle(centroid.x(), centroid.y() + grid_height, centroid.x() + grid_width,
-#     #                            centroid.y() + 2 * grid_height),
-#     #     "south": QgsRectangle(centroid.x(), centroid.y() - 2 * grid_height, centroid.x() + grid_width,
-#     #                              centroid.y() - grid_height),
-#     #     "west": QgsRectangle(centroid.x() - grid_width, centroid.y() - grid_height, centroid.x(),
-#     #                              centroid.y() + grid_height),
-#     #     "east": QgsRectangle(centroid.x() + grid_width, centroid.y() - grid_height, centroid.x() + 2 * grid_width,
-#     #                               centroid.y() + grid_height),
-#     # }
-#     # 查找邻居
-#     neighbors = {}
-#     for direction, neighbor_geom in neighbor_geometries.items():
-#         candidates = spatial_index.intersects(neighbor_geom)
-#         neighbors[direction] = int(
-#             any(layer.getFeature(fid).geometry().intersects(neighbor_geom) for fid in candidates))
-#     # 更新属性
-#     for direction, value in neighbors.items():
-#         if value == 0:
-#             feature[direction] = "自由"
-#         else:
-#             feature[direction] = None
-#     layer.updateFeature(feature)
-# # 保存编辑
-# layer.commitChanges()
-# print("邻居计算完成!")
+    # 遍历每一个Feature
+    for feature in layer.getFeatures():
+        # 获取每个Feature的几何信息
+        geometry = feature.geometry()
+
+        # 判断几何类型,如果是点类型,可以直接获取坐标
+        if geometry.type() == QgsWkbTypes.PointGeometry:
+            point = geometry.asPoint()  # 返回点的坐标 (x, y)
+            print(f"点坐标: {point}")
+
+        # 如果是线或面类型,获取所有坐标
+        elif geometry.type() == QgsWkbTypes.LineGeometry:
+            for point in geometry.asPolyline():  # 获取线的所有点
+                print(f"线坐标: {point}")
+
+        elif geometry.type() == QgsWkbTypes.PolygonGeometry:
+            rings = None
+            try:
+                rings = geometry.asPolygon()
+            except Exception as e:
+                rings = geometry.asMultiPolygon()
+                rings = rings[0]
+            finally:
+                print("读取完成")
+            for ring in rings:  # 获取面的所有点(包括外环和内环)
+                if len(ring) != 5:
+                    print("要素错误!")
+                    continue
+                print("开始计算")
+                p1 = ring[0]
+                p2 = ring[1]
+                p3 = ring[2]
+                p4 = ring[3]
+                # ymax = int((max(p1.x(), p2.x(), p3.x(), p4.x()) + D) / d) * d
+                # xmin = int((min(p1.x(), p2.x(), p3.x(), p4.x()) - D) / d) * d
+                # ymin = int((min(p1.y(), p2.y(), p3.y(), p4.y()) - D) / d) * d
+                # xmax = int((max(p1.y(), p2.y(), p3.y(), p4.y()) + D) / d) * d
+
+                ymax = int((max(p1.y(), p2.y(), p3.y(), p4.y()) + D) / d) * d
+                xmin = int((min(p1.x(), p2.x(), p3.x(), p4.x()) - D) / d) * d
+                ymin = int((min(p1.y(), p2.y(), p3.y(), p4.y()) - D) / d) * d
+                xmax = int((max(p1.x(), p2.x(), p3.x(), p4.x()) + D) / d) * d
+                
+                print(f"{xmin},{ymin},{xmax},{ymax}")
+                # for point in ring:
+                #     print(f"面坐标: {point}")