如何在pyQGIS中缓冲选定点
我有一些随机生成的点,这些点是在一个多边形内部的。我随机选了一个点,想要对这个点进行缓冲处理。但是在下面的例子中,缓冲处理是应用在所有的点上,而不是我选中的那个点。我是不是需要先为我选中的点创建一个新的内存图层?如果需要的话,我该怎么做呢?
#Generating random points within an "aoi" polygon file
pnts = processing.runAndLoadResults("native:randompointsinpolygons", {'INPUT':aoi,
'POINTS_NUMBER':10,
'MIN_DISTANCE':0,
'MIN_DISTANCE_GLOBAL':0,
'MAX_TRIES_PER_POINT':10,
'SEED':None,
'INCLUDE_POLYGON_ATTRIBUTES':True,
'OUTPUT':'memory:'})
#Randomly Choose one of the Points
processing.run("qgis:randomselection",
{'INPUT':pnts['OUTPUT'],
'METHOD':0,'NUMBER':1})
#Buffering the point
pnt_buf = processing.runAndLoadResults("native:buffer",
{'INPUT':pnts,
'DISTANCE':3000,
'SEGMENTS':6,
'END_CAP_STYLE':0,
'JOIN_STYLE':1,
'MITER_LIMIT':3,
'DISSOLVE':True,
'SEPARATE_DISJOINT':False,
'OUTPUT':'memory:'})
1 个回答
0
你不一定要通过一个中间的内存层来处理数据(不过你可以这么做)。其实你只需要稍微改动一下,修改一下缓冲处理工具的输入值,像下面这样。
首先获取一个 QgsVectorLayer 实例(在这里用你原来的代码):
pnts_0 = iface.activeLayer()
然后设置你的 'pnts' 输入,只使用选中的特征:
pnts = QgsProcessingFeatureSourceDefinition(pnts_0.id(), selectedFeaturesOnly=True, featureLimit=-1, geometryCheck=QgsFeatureRequest.GeometryAbortOnInvalid)
对点进行缓冲处理
pnt_buf = processing.runAndLoadResults("native:buffer",
{'INPUT':pnts,
'DISTANCE':3000,
'SEGMENTS':6,
'END_CAP_STYLE':0,
'JOIN_STYLE':1,
'MITER_LIMIT':3,
'DISSOLVE':True,
'SEPARATE_DISJOINT':False,
'OUTPUT':'memory:'})
编辑:
其实我有点无聊,又玩了一下,你可以试试这样做:
class randomBufferedPoint():
def randpoints(self, layer, num:int): # Note I added Num so you can modify the number of points when calling the method.
return processing.runAndLoadResults("native:randompointsinpolygons", {'INPUT':layer,
'POINTS_NUMBER':num,
'MIN_DISTANCE':0,
'MIN_DISTANCE_GLOBAL':0,
'MAX_TRIES_PER_POINT':10,
'SEED':None,
'INCLUDE_POLYGON_ATTRIBUTES':True,
'OUTPUT':'memory:'})
def randsel(self, layer, num:int): # Note I added Num so you can modify the number of points to select.
return processing.run("qgis:randomselection",
{'INPUT':layer,
'METHOD':0,'NUMBER':num})
def bufthis(self, layer, dist:int): # Note I added dist so you can modify the distance for the buffer
return processing.runAndLoadResults("native:buffer",
{'INPUT':layer,
'DISTANCE':dist,
'SEGMENTS':6,
'END_CAP_STYLE':0,
'JOIN_STYLE':1,
'MITER_LIMIT':3,
'DISSOLVE':True,
'SEPARATE_DISJOINT':False,
'OUTPUT':'memory:'})
rbp = randomBufferedPoint()
proj = QgsProject.instance()
lyr = proj.mapLayersByName('aoi')[0]
pts_layer = proj.mapLayer(rbp.randpoints(lyr, 5)['OUTPUT'])
sel_elems = rbp.randsel(pts_layer, 3)['OUTPUT']
pnts = QgsProcessingFeatureSourceDefinition(sel_elems.id(), selectedFeaturesOnly=True, featureLimit=-1, geometryCheck=QgsFeatureRequest.GeometryAbortOnInvalid)
rbp.bufthis(pnts, 5000)
但显然,这取决于你想怎么应用或整合这段代码。