def update(self): # inputs points_in = [] if 'Vertices' in self.inputs and len(self.inputs['Vertices'].links)>0: if not self.inputs['Vertices'].node.socket_value_update: self.inputs['Vertices'].node.update() points_in = eval(self.inputs['Vertices'].links[0].from_socket.VerticesProperty) tris_out=[] edges_out=[] for obj in points_in: pt_list = [] for pt in obj: pt_list.append(Site(pt[0],pt[1])) # print("obj",obj,pt_list) res = computeDelaunayTriangulation(pt_list) tris_out.append([tri for tri in res if -1 not in tri] ) if 'Edges' in self.outputs and len(self.outputs['Edges'].links)>0: if not self.outputs['Edges'].node.socket_value_update: self.outputs['Edges'].node.update() self.outputs['Edges'].StringsProperty = str(edges_out) if 'Polygons' in self.outputs and len(self.outputs['Polygons'].links)>0: if not self.outputs['Polygons'].node.socket_value_update: self.outputs['Polygons'].node.update() self.outputs['Polygons'].StringsProperty = str(tris_out)
def main(): global opts (progdir, progname) = os.path.split(sys.argv[0]) usage = "usage: %prog [options] file.stl" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() points = readpoints() if opts.inifile: import linuxcnc inifile = linuxcnc.ini(opts.inifile) lu = inifile.find("TRAJ", "LINEAR_UNITS") if lu.lower() in ("mm", "metric"): units = 1.0 else: units = 25.4 xmin = float(inifile.find("AXIS_0", "MIN_LIMIT")) * units ymin = float(inifile.find("AXIS_1", "MIN_LIMIT")) * units xmax = float(inifile.find("AXIS_0", "MAX_LIMIT")) * units ymax = float(inifile.find("AXIS_1", "MAX_LIMIT")) * units zbound = 0 if opts.zbound: zbound = opts.zbound points.append(Point(xmin, ymin, zbound)) points.append(Point(xmax, ymax, zbound)) points.append(Point(xmin, ymax, zbound)) points.append(Point(xmax, ymin, zbound)) triangles = voronoi.computeDelaunayTriangulation(points) stldump(sys.stdout, points, triangles)
def __init__(self, margin=60, dims=WINDOW_SIZE): self.dims = Size(*dims) self.min_distance = sum(dims) / 18 self.margin = margin points = [ Coords(floor(x) + self.margin, floor(y) + self.margin) for x, y in sample_poisson_uniform(self.dims.w - self.margin * 2, self.dims.h - self.margin * 2, self.min_distance, # Sample points for Poisson, arbitrary 30) ] self.graph = nx.Graph() self.graph.add_nodes_from(points) for triangle in computeDelaunayTriangulation(points): self.graph.add_edges_from(chain(*[ [(points[firstIndex], points[secondIndex]), (points[secondIndex], points[firstIndex])] for firstIndex, secondIndex in combinations(triangle, 2) ])) wall_crossings, self.wall_dict = self.computeWalls() self.walls = [cross.wall for cross in wall_crossings] self.removeMultiWallEdges() self.addCrossings(wall_crossings) # can't use edges_iter here since we're modifying it dist_squared = self.min_distance ** 2 for v1, v2, attrs in self.graph.edges(data=True): if distance_squared(v1, v2) > 2 * dist_squared: self.graph.remove_edge(v1, v2) if not nx.is_connected(self.graph): self.graph.add_edge(v1, v2, attrs)
def plotDelaunay(inputpoints): points = preparePoints(inputpoints) results = voronoi.computeDelaunayTriangulation(points) curves = [] for result in results: curves.append(rs.AddLine([points[result[0]].x, points[result[0]].y, 0], [points[result[1]].x, points[result[1]].y, 0])) curves.append(rs.AddLine([points[result[1]].x, points[result[1]].y, 0], [points[result[2]].x, points[result[2]].y, 0])) curves.append(rs.AddLine([points[result[2]].x, points[result[2]].y, 0], [points[result[0]].x, points[result[0]].y, 0])) return curves
def calc_delaunay(self,points): d = voronoi.computeDelaunayTriangulation(points) col = (255,0,0) for t in range(len(d)): tri = d[t] l1 = (points[tri[0]].x(),points[tri[0]].y(),points[tri[1]].x(),points[tri[1]].y()) self.draw_line(l1,col) l2 = (points[tri[1]].x(),points[tri[1]].y(),points[tri[2]].x(),points[tri[2]].y()) self.draw_line(l2,col) l3 = (points[tri[2]].x(),points[tri[2]].y(),points[tri[0]].x(),points[tri[0]].y()) self.draw_line(l3,col)
def update(self): points_in = [] if not ('Polygons' in self.outputs and self.outputs['Polygons'].links): return if 'Vertices' in self.inputs and self.inputs['Vertices'].links: points_in = SvGetSocketAnyType(self,self.inputs['Vertices']) tris_out=[] for obj in points_in: pt_list = [Site(pt[0],pt[1]) for pt in obj] res = computeDelaunayTriangulation(pt_list) tris_out.append([tri for tri in res if -1 not in tri] ) if 'Polygons' in self.outputs and self.outputs['Polygons'].links: SvSetSocketAnyType(self,'Polygons',tris_out)
def update(self): points_in = [] if not ('Polygons' in self.outputs and self.outputs['Polygons'].links): return if 'Vertices' in self.inputs and self.inputs['Vertices'].links: points_in = SvGetSocketAnyType(self, self.inputs['Vertices']) tris_out = [] for obj in points_in: pt_list = [Site(pt[0], pt[1]) for pt in obj] res = computeDelaunayTriangulation(pt_list) tris_out.append([tri for tri in res if -1 not in tri]) if 'Polygons' in self.outputs and self.outputs['Polygons'].links: SvSetSocketAnyType(self, 'Polygons', tris_out)
def delaunay_triangulation(self, writer, provider, points): triangles = voronoi.computeDelaunayTriangulation(points) all_attrs = provider.attributeIndexes() provider.select(all_attrs) feat = QgsFeature() for triangle in triangles: indicies = list(triangle) indicies.append(indicies[0]) polygon = [] for index in indicies: provider.featureAtId(index, feat, True, all_attrs) geom = QgsGeometry(feat.geometry()) point = QgsPoint(geom.asPoint()) polygon.append(point) geometry = QgsGeometry().fromPolygon([polygon]) feat.setGeometry(geometry) writer.addFeature(feat) del writer
def delaunay_triangulation( self ): import voronoi vprovider = self.vlayer.dataProvider() allAttrs = vprovider.attributeIndexes() vprovider.select( allAttrs ) fields = { 0 : QgsField( "POINTA", QVariant.Double ), 1 : QgsField( "POINTB", QVariant.Double ), 2 : QgsField( "POINTC", QVariant.Double ) } writer = QgsVectorFileWriter( self.myName, self.myEncoding, fields, QGis.WKBPolygon, vprovider.crs() ) inFeat = QgsFeature() points = [] while vprovider.nextFeature( inFeat ): inGeom = QgsGeometry( inFeat.geometry() ) point = inGeom.asPoint() points.append( point ) vprovider.rewind() vprovider.select( allAttrs ) triangles = voronoi.computeDelaunayTriangulation( points ) feat = QgsFeature() nFeat = len( triangles ) nElement = 0 self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), 0 ) self.emit( SIGNAL( "runRange(PyQt_PyObject)" ), ( 0, nFeat ) ) for triangle in triangles: indicies = list( triangle ) indicies.append( indicies[ 0 ] ) polygon = [] step = 0 for index in indicies: vprovider.featureAtId( index, inFeat, True, allAttrs ) geom = QgsGeometry( inFeat.geometry() ) point = QgsPoint( geom.asPoint() ) polygon.append( point ) if step <= 3: feat.addAttribute( step, QVariant( index ) ) step += 1 geometry = QgsGeometry().fromPolygon( [ polygon ] ) feat.setGeometry( geometry ) writer.addFeature( feat ) nElement += 1 self.emit( SIGNAL( "runStatus(PyQt_PyObject)" ), nElement ) del writer return True
def effect(self): #{{{ Check that elements have been selected if len(self.options.ids) == 0: inkex.errormsg(_("Please select objects!")) return #}}} #{{{ Drawing styles linestyle = { 'stroke' : '#000000', 'stroke-width' : str(self.unittouu('1px')), 'fill' : 'none' } facestyle = { 'stroke' : '#ff0000', 'stroke-width' : str(self.unittouu('1px')), 'fill' : 'none' } #}}} #{{{ Handle the transformation of the current group parentGroup = self.getParentNode(self.selected[self.options.ids[0]]) trans = self.getGlobalTransform(parentGroup) invtrans = None if trans: invtrans = simpletransform.invertTransform(trans) #}}} #{{{ Recovery of the selected objects pts = [] nodes = [] seeds = [] for id in self.options.ids: node = self.selected[id] nodes.append(node) bbox = simpletransform.computeBBox([node]) if bbox: cx = 0.5*(bbox[0]+bbox[1]) cy = 0.5*(bbox[2]+bbox[3]) pt = [cx,cy] if trans: simpletransform.applyTransformToPoint(trans,pt) pts.append(Point(pt[0],pt[1])) seeds.append(Point(cx,cy)) #}}} #{{{ Creation of groups to store the result if self.options.diagramType != 'Delaunay': # Voronoi groupVoronoi = inkex.etree.SubElement(parentGroup,inkex.addNS('g','svg')) groupVoronoi.set(inkex.addNS('label', 'inkscape'), 'Voronoi') if invtrans: simpletransform.applyTransformToNode(invtrans,groupVoronoi) if self.options.diagramType != 'Voronoi': # Delaunay groupDelaunay = inkex.etree.SubElement(parentGroup,inkex.addNS('g','svg')) groupDelaunay.set(inkex.addNS('label', 'inkscape'), 'Delaunay') #}}} #{{{ Clipping box handling if self.options.diagramType != 'Delaunay': #Clipping bounding box creation gBbox = simpletransform.computeBBox(nodes) #Clipbox is the box to which the Voronoi diagram is restricted clipBox = () if self.options.clipBox == 'Page': svg = self.document.getroot() w = self.unittouu(svg.get('width')) h = self.unittouu(svg.get('height')) clipBox = (0,w,0,h) else: clipBox = (2*gBbox[0]-gBbox[1], 2*gBbox[1]-gBbox[0], 2*gBbox[2]-gBbox[3], 2*gBbox[3]-gBbox[2]) #Safebox adds points so that no Voronoi edge in clipBox is infinite safeBox = (2*clipBox[0]-clipBox[1], 2*clipBox[1]-clipBox[0], 2*clipBox[2]-clipBox[3], 2*clipBox[3]-clipBox[2]) pts.append(Point(safeBox[0],safeBox[2])) pts.append(Point(safeBox[1],safeBox[2])) pts.append(Point(safeBox[1],safeBox[3])) pts.append(Point(safeBox[0],safeBox[3])) if self.options.showClipBox: #Add the clip box to the drawing rect = inkex.etree.SubElement(groupVoronoi,inkex.addNS('rect','svg')) rect.set('x',str(clipBox[0])) rect.set('y',str(clipBox[2])) rect.set('width',str(clipBox[1]-clipBox[0])) rect.set('height',str(clipBox[3]-clipBox[2])) rect.set('style',simplestyle.formatStyle(linestyle)) #}}} #{{{ Voronoi diagram generation if self.options.diagramType != 'Delaunay': vertices,lines,edges = voronoi.computeVoronoiDiagram(pts) for edge in edges: line = edge[0] vindex1 = edge[1] vindex2 = edge[2] if (vindex1 <0) or (vindex2 <0): continue # infinite lines have no need to be handled in the clipped box else: segment = self.clipEdge(vertices,lines,edge,clipBox) #segment = [vertices[vindex1],vertices[vindex2]] # deactivate clipping if len(segment)>1: v1 = segment[0] v2 = segment[1] cmds = [['M',[v1[0],v1[1]]],['L',[v2[0],v2[1]]]] path = inkex.etree.Element(inkex.addNS('path','svg')) path.set('d',simplepath.formatPath(cmds)) path.set('style',simplestyle.formatStyle(linestyle)) groupVoronoi.append(path) if self.options.diagramType != 'Voronoi': triangles = voronoi.computeDelaunayTriangulation(seeds) for triangle in triangles: p1 = seeds[triangle[0]] p2 = seeds[triangle[1]] p3 = seeds[triangle[2]] cmds = [['M',[p1.x,p1.y]], ['L',[p2.x,p2.y]], ['L',[p3.x,p3.y]], ['Z',[]]] path = inkex.etree.Element(inkex.addNS('path','svg')) path.set('d',simplepath.formatPath(cmds)) path.set('style',simplestyle.formatStyle(facestyle)) groupDelaunay.append(path)
f = open(archive, "rb") triangles = pickle.load(f) f.close() # Open LIDAR LAS file las = File(source, mode="r") else: # Open LIDAR LAS file las = File(source, mode="r") points = [] print("Assembling points...") # Pull points from LAS file for x, y in np.nditer((las.x, las.y)): points.append(Point(x, y)) print("Composing triangles...") # Delaunay Triangulation triangles = voronoi.computeDelaunayTriangulation(points) # Save the triangles to save time if we write more than # one shapefile. f = open(archive, "wb") pickle.dump(triangles, f, protocol=2) f.close() print("Creating shapefile...") w = None if os.path.exists(pyshp): f = open(pyshp, "rb") w = pickle.load(f) f.close() else: # PolygonZ shapefile (x, y, z, m) w = shapefile.Writer(shapefile.POLYGONZ)
def computeDelaunayTriangulation(): global points; return voronoi.computeDelaunayTriangulation(points);
def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. # pass edit_distanza = self.dlg.findChild(QLineEdit, "edit_distanza") distanza = float(edit_distanza.text()) # checkBox_IncludiPuntiOriginali = self.dlg.findChild(QCheckBox,"checkBox_IncludiPuntiOriginali") # if checkBox_IncludiPuntiOriginali.isChecked() == True: # IncludiPuntiOriginali = int(1) # else: # IncludiPuntiOriginali = int(0) checkBox_MostraTriangoliEsterni = self.dlg.findChild( QCheckBox, "checkBox_MostraTriangoliEsterni") if checkBox_MostraTriangoliEsterni.isChecked() == True: MostraTriangoliEsterni = int(1) else: MostraTriangoliEsterni = int(0) # distanza = 15.00 # <----------- RISOLUZIONE (modificabile) # misura = 9.00 canvas = self.iface.mapCanvas() layer = canvas.currentLayer() if (layer == NULL): self.iface.messageBar().pushMessage( "WARNING", "No active vector layer!!!", level=QgsMessageBar.WARNING, duration=3) return if layer.type() != layer.VectorLayer: self.iface.messageBar().pushMessage( "WARNING", "You need to have a vector Point layer active !!!", level=QgsMessageBar.WARNING, duration=3) return crs = layer.crs() if (crs.authid() == "EPSG:4326"): dist = distanza / 100000 else: dist = distanza provider = layer.dataProvider() #-------------------------------------------------------- geomType = ("Point" + '?crs=%s') % (crs.authid()) DronePlan = "ISR_Points_" + str(distanza) + "_m" memLay_Point = QgsVectorLayer(geomType, DronePlan, 'memory') memprovider_Point = memLay_Point.dataProvider() memLay_Point.updateExtents() memLay_Point.commitChanges() QgsMapLayerRegistry.instance().addMapLayer(memLay_Point) res = memprovider_Point.addAttributes([ QgsField("ID", QVariant.String), QgsField("xo", QVariant.String), QgsField("yo", QVariant.String), QgsField("triangle", QVariant.String), QgsField("triaord", QVariant.String), QgsField("internal", QVariant.String), QgsField("mediana", QVariant.String), QgsField("misura", QVariant.String) ]) #-------------------------------------------------------- # geomType = ("Polygon" + '?crs=%s') %(crs.authid()) # DronePlan = "ISR_Tin_" + str(distanza) + "_m" # memLay_Tin = QgsVectorLayer(geomType, DronePlan, 'memory') # memprovider_Tin = memLay_Tin.dataProvider() # # memLay_Tin.updateExtents() # memLay_Tin.commitChanges() # QgsMapLayerRegistry.instance().addMapLayer(memLay_Tin) # res = memprovider_Tin.addAttributes( [ QgsField("nPoligono", QVariant.String), QgsField("lato", QVariant.String), QgsField("xo", QVariant.String), QgsField("yo", QVariant.String), QgsField("triangle", QVariant.String), QgsField("triaord", QVariant.String), QgsField("internal", QVariant.String), QgsField("mediana", QVariant.String), QgsField("misura", QVariant.String)] ) #-------------------------------------------------------- # geomType = ("Point" + '?crs=%s') %(crs.authid()) # DronePlan = "ISR_SpinePoints_" + str(distanza) + "_m" # memLay_SpinePoints = QgsVectorLayer(geomType, DronePlan, 'memory') # memprovider_SpinePoints = memLay_SpinePoints.dataProvider() # # memLay_SpinePoints.updateExtents() # memLay_SpinePoints.commitChanges() # QgsMapLayerRegistry.instance().addMapLayer(memLay_SpinePoints) # res = memprovider_SpinePoints.addAttributes( [ QgsField("nPoligono", QVariant.String), QgsField("COD_VARIET", QVariant.String), QgsField("lato", QVariant.String), QgsField("xo", QVariant.String), QgsField("yo", QVariant.String), QgsField("triangle", QVariant.String), QgsField("triaord", QVariant.String), QgsField("internal", QVariant.String), QgsField("mediana", QVariant.String), QgsField("misura", QVariant.String)] ) #-------------------------------------------------------- # geomType = ("LineString" + '?crs=%s') %(crs.authid()) # DronePlan = "ISR_SpineLine_" + str(distanza) + "_m" # memLay_SpineLine = QgsVectorLayer(geomType, DronePlan, 'memory') # memprovider_SpineLine = memLay_SpineLine.dataProvider() # # memLay_SpineLine.updateExtents() # memLay_SpineLine.commitChanges() # QgsMapLayerRegistry.instance().addMapLayer(memLay_SpineLine) # res = memprovider_SpineLine.addAttributes( [ QgsField("nPoligono", QVariant.String), QgsField("COD_VARIET", QVariant.String), QgsField("lato", QVariant.String), QgsField("xo", QVariant.String), QgsField("yo", QVariant.String), QgsField("triangle", QVariant.String), QgsField("triaord", QVariant.String), QgsField("internal", QVariant.String), QgsField("mediana", QVariant.String), QgsField("misura", QVariant.String), QgsField("lunghezza", QVariant.String), QgsField("IdClass", QVariant.String)] ) #-------------------------------------------------------- styledir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "python/plugins/isorange/_QML_Styles" memLay_Point.loadNamedStyle(styledir + '/ISR_Points.qml') # memLay_Tin.loadNamedStyle(styledir + '/ISR_TIN.qml') # memLay_SpineLine.loadNamedStyle(styledir + '/ISR_SpineLine.qml') #-------------------------------------------------------- # retreive every feature (or selected features) with its geometry and attributes nPoligono = 0 nElement = 0 count = layer.selectedFeatureCount() if (count != 0): iter = layer.selectedFeatures() else: iter = layer.getFeatures() # EndIf points = [] poly = [] distance = float(distanza) for feat in iter: nPoligono = nPoligono + 1 # fetch geometry geom = feat.geometry() # show some information about the feature if geom.type() == QGis.Point: elem = geom.asPoint() point = elem points.append(point) poly.append(point) elif geom.type() == QGis.Line: self.iface.messageBar().pushMessage( "WARNING", "You need to have a vector Point layer active !!!", level=QgsMessageBar.WARNING, duration=3) return elif geom.type() == QGis.Polygon: self.iface.messageBar().pushMessage( "WARNING", "You need to have a vector Point layer active !!!", level=QgsMessageBar.WARNING, duration=3) return # End For ################ # Delaunay Triangulation----------------------------------------- # Costruisco il poligono esterno ################ # print ("DIST DIST*3 LENGTH %s %s %s") %(dist, dist*3, perimetro) if (nPoligono): msg = ("Poligono %s") % (nPoligono) self.iface.mainWindow().statusBar().showMessage(msg) polEsterno = Polygon(poly) # Calcola il TIN # print points triangles = voronoi.computeDelaunayTriangulation(points) msg = ("Delaunay %s") % (nPoligono) self.iface.mainWindow().statusBar().showMessage(msg) feat = QgsFeature() featSpinePoint = QgsFeature() featSpineLine = QgsFeature() nFeat = len(triangles) nElement = 0 # Disegna i triangoli (solo se contenuti nel poligono) ###################! for triangle in triangles: indicies = list(triangle) # Metto gli indici in ordine crescente ind0 = indicies[0] ind1 = indicies[1] ind2 = indicies[2] x0 = points[ind0].x() y0 = points[ind0].y() x1 = points[ind1].x() y1 = points[ind1].y() x2 = points[ind2].x() y2 = points[ind2].y() lato = 0 xa = x0 ya = y0 xb = x2 yb = y2 xc = x1 yc = y1 dxAB = (xb - xa) dyAB = (yb - ya) dxBC = (xc - xb) dyBC = (yc - yb) dxCA = (xa - xc) dyCA = (ya - yc) distAB = math.sqrt(dxAB * dxAB + dyAB * dyAB) distBC = math.sqrt(dxBC * dxBC + dyBC * dyBC) distCA = math.sqrt(dxCA * dxCA + dyCA * dyCA) tria = ("%s %s %s %s") % (nPoligono, ind0, ind1, ind2) triaord = ("%05d %05d %05d %05d") % (nPoligono, ind0, ind1, ind2) xCenAC = (xa + xc) / 2. # questo è il punto centrale del lato yCenAC = (ya + yc) / 2. xo = (xCenAC + xb) / 2. # questo è il punto centrale della mediana yo = (yCenAC + yb) / 2. pun = Point(xo, yo) dentro = polEsterno.contains(pun) mediana = 0 internal = '0' if ((dentro == True)): internal = '1' if (distAB < distance): Point1 = QgsGeometry.fromPoint(QgsPoint(xa, ya)) Point2 = QgsGeometry.fromPoint(QgsPoint(xb, yb)) dista = distAB feat.setGeometry(Point1) feat.initAttributes(8) values = [(ind0), (xa), (ya), (tria), (triaord), (internal), (mediana), (dista)] feat.setAttributes(values) memprovider_Point.addFeatures([feat]) feat.setGeometry(Point2) feat.initAttributes(8) values = [(ind1), (xb), (yb), (tria), (triaord), (internal), (mediana), (dista)] feat.setAttributes(values) memprovider_Point.addFeatures([feat]) if (distBC < distance): Point1 = QgsGeometry.fromPoint(QgsPoint(xc, yc)) Point2 = QgsGeometry.fromPoint(QgsPoint(xb, yb)) dista = distBC feat.setGeometry(Point1) feat.initAttributes(8) values = [(ind2), (xc), (yc), (tria), (triaord), (internal), (mediana), (dista)] feat.setAttributes(values) memprovider_Point.addFeatures([feat]) feat.setGeometry(Point2) feat.initAttributes(8) values = [(ind1), (xb), (yb), (tria), (triaord), (internal), (mediana), (dista)] feat.setAttributes(values) memprovider_Point.addFeatures([feat]) if (distCA < distance): Point1 = QgsGeometry.fromPoint(QgsPoint(xa, ya)) Point2 = QgsGeometry.fromPoint(QgsPoint(xc, yc)) dista = distCA feat.setGeometry(Point1) feat.initAttributes(8) values = [(ind0), (xa), (ya), (tria), (triaord), (internal), (mediana), (dista)] feat.setAttributes(values) memprovider_Point.addFeatures([feat]) feat.setGeometry(Point2) feat.initAttributes(8) values = [(ind2), (xc), (yc), (tria), (triaord), (internal), (mediana), (dista)] feat.setAttributes(values) memprovider_Point.addFeatures([feat]) # ----------------------! ###################! ################ msg = ("SpineLine %s") % (nPoligono) self.iface.mainWindow().statusBar().showMessage(msg) nElement += 1 memLay_Point.updateFields() # memLay_Tin.updateFields() # memLay_SpinePoints.updateFields() # memLay_SpineLine.updateFields() ################ #if dista*3 <= length: # memLay_Tin.updateExtents() msg = ("Terminati Poligoni %s") % (nPoligono) self.iface.messageBar().pushMessage("IsoRange: ", msg, QgsMessageBar.INFO, 3) canvas.refresh()
def effect(self): # Check that elements have been selected if not self.svg.selected: inkex.errormsg(_("Please select objects!")) return linestyle = { 'stroke': '#000000', 'stroke-width': str(self.svg.unittouu('1px')), 'fill': 'none', 'stroke-linecap': 'round', 'stroke-linejoin': 'round' } facestyle = { 'stroke': '#000000', 'stroke-width': str(self.svg.unittouu('1px')), 'fill': 'none', 'stroke-linecap': 'round', 'stroke-linejoin': 'round' } parent_group = self.svg.selection.first().getparent() trans = parent_group.composed_transform() invtrans = None if trans: invtrans = -trans # Recovery of the selected objects pts = [] nodes = [] seeds = [] fills = [] for node in self.svg.selected.values(): nodes.append(node) bbox = node.bounding_box() if bbox: center_x, center_y = bbox.center point = [center_x, center_y] if trans: point = trans.apply_to_point(point) pts.append(Point(*point)) if self.options.delaunayFillOptions != "delaunay-no-fill": fills.append(node.style.get('fill', 'none')) seeds.append(Point(center_x, center_y)) # Creation of groups to store the result if self.options.diagramType != 'Delaunay': # Voronoi group_voronoi = parent_group.add(Group()) group_voronoi.set('inkscape:label', 'Voronoi') if invtrans: group_voronoi.transform *= invtrans if self.options.diagramType != 'Voronoi': # Delaunay group_delaunay = parent_group.add(Group()) group_delaunay.set('inkscape:label', 'Delaunay') # Clipping box handling if self.options.diagramType != 'Delaunay': # Clipping bounding box creation group_bbox = sum([node.bounding_box() for node in nodes], None) # Clipbox is the box to which the Voronoi diagram is restricted if self.options.clip_box == 'Page': svg = self.document.getroot() width = self.svg.unittouu(svg.get('width')) height = self.svg.unittouu(svg.get('height')) clip_box = (0, width, 0, height) else: clip_box = (group_bbox.left, group_bbox.right, group_bbox.top, group_bbox.bottom) # Safebox adds points so that no Voronoi edge in clip_box is infinite safe_box = (2 * clip_box[0] - clip_box[1], 2 * clip_box[1] - clip_box[0], 2 * clip_box[2] - clip_box[3], 2 * clip_box[3] - clip_box[2]) pts.append(Point(safe_box[0], safe_box[2])) pts.append(Point(safe_box[1], safe_box[2])) pts.append(Point(safe_box[1], safe_box[3])) pts.append(Point(safe_box[0], safe_box[3])) if self.options.showClipBox: # Add the clip box to the drawing rect = group_voronoi.add(Rectangle()) rect.set('x', str(clip_box[0])) rect.set('y', str(clip_box[2])) rect.set('width', str(clip_box[1] - clip_box[0])) rect.set('height', str(clip_box[3] - clip_box[2])) rect.style = linestyle # Voronoi diagram generation if self.options.diagramType != 'Delaunay': vertices, lines, edges = voronoi.computeVoronoiDiagram(pts) for edge in edges: vindex1, vindex2 = edge[1:] if (vindex1 < 0) or (vindex2 < 0): continue # infinite lines have no need to be handled in the clipped box else: segment = self.clip_edge(vertices, lines, edge, clip_box) # segment = [vertices[vindex1],vertices[vindex2]] # deactivate clipping if len(segment) > 1: x1, y1 = segment[0] x2, y2 = segment[1] cmds = [['M', [x1, y1]], ['L', [x2, y2]]] path = group_voronoi.add(PathElement()) path.set('d', str(inkex.Path(cmds))) path.style = linestyle if self.options.diagramType != 'Voronoi': triangles = voronoi.computeDelaunayTriangulation(seeds) i = 0 if self.options.delaunayFillOptions == "delaunay-fill": random.seed("inkscape") for triangle in triangles: pt1 = seeds[triangle[0]] pt2 = seeds[triangle[1]] pt3 = seeds[triangle[2]] cmds = [['M', [pt1.x, pt1.y]], ['L', [pt2.x, pt2.y]], ['L', [pt3.x, pt3.y]], ['Z', []]] if self.options.delaunayFillOptions == "delaunay-fill" \ or self.options.delaunayFillOptions == "delaunay-fill-random": facestyle = { 'stroke': fills[triangle[random.randrange(0, 2)]], 'stroke-width': str(self.svg.unittouu('0.005px')), 'fill': fills[triangle[random.randrange(0, 2)]], 'stroke-linecap': 'round', 'stroke-linejoin': 'round' } path = group_delaunay.add(PathElement()) path.set('d', str(inkex.Path(cmds))) path.style = facestyle i += 1
def findNeighbourOnMinRadiusMultiplyN(pointList, MULTRADIUS=2): ''' Find neigbour for every point in pointlist (point must have .x and .y properties) Result is list with tuples, tuple linked with points in pointList by same indexes First element in tuple is minRadius of point, which means distance to nearest other point Second element in tuple is set of point indexes, which lay in MULTRADIUS*minRadius to point [(1.1661903789690602, set([1])), (1.1661903789690602, set([0, 3])), (3.1622776601683795, set([0, 1, 3, 4, 6])), (2.039607805437114, set([0, 1, 2, 4])), (1.4142135623730951, set([3, 5])), (1.4142135623730951, set([4])), (4.47213595499958, set([0, 1, 2, 3, 4, 5]))] ''' threeTuple = voronoi.computeDelaunayTriangulation(pointList) @memoize_sorted def findDistance(indexPoint1, indexPoint2): return sqrt(pow((pointList[indexPoint2].x - pointList[indexPoint1].x), 2) + pow((pointList[indexPoint2].y - pointList[indexPoint1].y), 2)) #print(findDistance(2, 4), 'dist between i2 and i4 points') # for points = [(2,3), (3,3.6), (4,7), (5,4), (7,2), (8,1), (9,6)] #print(findDistance(3, 6)) # print(findDistance(4, 6)) # print(pointList[3], pointList[4], pointList[6]) # for points = [(2,3), (3,3.6), (4,7), (5,4), (7,2), (8,1), (9,6)] # and MULTIRADIUS = 1 resultListOfDict = [{} for i in range(0, len(pointList))] resultNeighbourList = [] resultNeighbourListWithSets = [] #get all connections and calc dist for tup in threeTuple: for i in range(0, 3): for j in range(0, 3): if i != j: resultListOfDict[tup[i]].update({tup[j]:findDistance(tup[i], tup[j])}) #print(resultListOfDict) for iDict, pointConnectionDict in enumerate(resultListOfDict): #print(iDict, pointConnectionDict) indexPointToCompute = [] computedIndexPoints = pointConnectionDict.keys() #print(pointConnectionDict, pointConnectionDict.keys(), pointConnectionDict.values()) neighboursMRIndexses = [] r = min(pointConnectionDict.values()) mr = r*MULTRADIUS #print(r, mr) for indexPoint in pointConnectionDict.keys(): ''' first check nearest points of iDict point ''' #print(indexPoint) computedIndexPoints.append(indexPoint) if pointConnectionDict[indexPoint] <= mr: ''' if point is neighbour, append linked other points to indexPointToCompute also check for already computed points ''' neighboursMRIndexses.append(indexPoint) checkIndexes = resultListOfDict[indexPoint].keys() for ele in checkIndexes: if ele not in computedIndexPoints: indexPointToCompute.append(ele) while len(indexPointToCompute) > 0: ''' go through linked to neighbour points and checking if it is neighbour, then add to cycle linked to new neighbour points ''' nextIndexPoint = indexPointToCompute.pop(0) dist = findDistance(nextIndexPoint, iDict) computedIndexPoints.append(nextIndexPoint) if dist <= mr: neighboursMRIndexses.append(nextIndexPoint) checkIndexes = resultListOfDict[nextIndexPoint].keys() for ele in checkIndexes: if ele not in computedIndexPoints: indexPointToCompute.append(ele) ''' remove duplicates and point whom we calc from neighboursMRIndexses ''' setToAdd = set(neighboursMRIndexses) if iDict in setToAdd: setToAdd.remove(iDict) resultNeighbourList.append((r, neighboursMRIndexses)) resultNeighbourListWithSets.append((r, setToAdd)) #print(iDict, neighboursMRIndexses, setToAdd, 'neighbourd', mr) return resultNeighbourListWithSets #resultNeighbourList
f = open(archive, "rb") triangles = cPickle.load(f) f.close() # Open LIDAR LAS file las = File(source, mode="r") else: # Open LIDAR LAS file las = File(source, mode="r") points = [] print "Assembling points..." # Pull points from LAS file for x, y in np.nditer((las.x, las.y)): points.append(Point(x, y)) print "Composing triangles..." # Delaunay Triangulation triangles = voronoi.computeDelaunayTriangulation(points) # Save the triangles to save time if we write more than # one shapefile. f = open(archive, "wb") cPickle.dump(triangles, f, protocol=2) f.close() print "Creating shapefile..." w = None if os.path.exists(pyshp): f = open(pyshp, "rb") w = cPickle.load(f) f.close() else: # PolygonZ shapefile (x,y,z,m) w = shapefile.Writer(shapefile.POLYGONZ)
def effect(self): # Check that elements have been selected if len(self.options.ids) == 0: inkex.errormsg("Please select objects!") return # Drawing styles linestyle = { 'stroke': '#000000', 'stroke-width': str(self.svg.unittouu('1px')), 'fill': 'none' } facestyle = { 'stroke': '#000000', 'stroke-width': '0px', # str(self.svg.unittouu('1px')), 'fill': 'none' } # Handle the transformation of the current group parentGroup = (self.svg.selected[self.options.ids[0]]).getparent() svg = self.document.getroot() image_element = svg.find('.//{http://www.w3.org/2000/svg}image') if image_element is None: inkex.utils.debug("No image found") exit(1) self.path = self.checkImagePath( image_element) # This also ensures the file exists if self.path is None: # check if image is embedded or linked image_string = image_element.get( '{http://www.w3.org/1999/xlink}href') # find comma position i = 0 while i < 40: if image_string[i] == ',': break i = i + 1 img = Image.open( BytesIO(base64.b64decode(image_string[i + 1:len(image_string)]))) else: img = Image.open(self.path) extrinsic_image_width = float(image_element.get('width')) extrinsic_image_height = float(image_element.get('height')) (width, height) = img.size trans = self.getGlobalTransform(parentGroup) invtrans = None if trans: invtrans = self.invertTransform(trans) # Recovery of the selected objects pts = [] nodes = [] seeds = [] for id in self.options.ids: node = self.svg.selected[id] nodes.append(node) if (node.tag == "{http://www.w3.org/2000/svg}path" ): #If it is path # Get vertex coordinates of path points = CubicSuperPath(node.get('d')) for p in points[0]: pt = [p[1][0], p[1][1]] if trans: Transform(trans).apply_to_point(pt) pts.append(Point(pt[0], pt[1])) seeds.append(Point(p[1][0], p[1][1])) else: # For other shapes bbox = node.bounding_box() if bbox: cx = 0.5 * (bbox.left + bbox.top) cy = 0.5 * (bbox.top + bbox.bottom) pt = [cx, cy] if trans: Transform(trans).apply_to_point(pt) pts.append(Point(pt[0], pt[1])) seeds.append(Point(cx, cy)) pts.sort() seeds.sort() # In Creation of groups to store the result # Delaunay groupDelaunay = etree.SubElement(parentGroup, inkex.addNS('g', 'svg')) groupDelaunay.set(inkex.addNS('label', 'inkscape'), 'Delaunay') scale_x = float(extrinsic_image_width) / float(width) scale_y = float(extrinsic_image_height) / float(height) # Voronoi diagram generation triangles = voronoi.computeDelaunayTriangulation(seeds) for triangle in triangles: p1 = seeds[triangle[0]] p2 = seeds[triangle[1]] p3 = seeds[triangle[2]] cmds = [['M', [p1.x, p1.y]], ['L', [p2.x, p2.y]], ['L', [p3.x, p3.y]], ['Z', []]] path = etree.Element(inkex.addNS('path', 'svg')) path.set('d', str(Path(cmds))) middleX = (p1.x + p2.x + p3.x) / 3.0 middleY = (p1.y + p2.y + p3.y) / 3.0 if width > middleX and height > middleY and middleX >= 0 and middleY >= 0: pixelColor = img.getpixel((middleX, middleY)) facestyle["fill"] = str( inkex.Color((pixelColor[0], pixelColor[1], pixelColor[2]))) else: facestyle["fill"] = "black" path.set('style', str(inkex.Style(facestyle))) groupDelaunay.append(path)
def triangulate(self): self.triangulation = voronoi.computeDelaunayTriangulation(self.src_vertices)
def triangulate(self): self.triangulation = voronoi.computeDelaunayTriangulation( self.src_vertices)
def effect(self): #{{{ Check that elements have been selected if len(self.options.ids) == 0: inkex.errormsg(_("Please select objects!")) return #}}} #{{{ Drawing styles linestyle = { 'stroke': '#000000', 'stroke-width': str(self.unittouu('1px')), 'fill': 'none' } facestyle = { 'stroke': '#000000', 'stroke-width':'0px',# str(self.unittouu('1px')), 'fill': 'none' } #}}} #{{{ Handle the transformation of the current group parentGroup = self.getParentNode(self.selected[self.options.ids[0]]) svg = self.document.getroot() children =svg.getchildren() fp=open("log.txt","w") img=None width_in_svg=1 height_in_svg=1 for child in children: if child.tag=="{http://www.w3.org/2000/svg}g": ccc=child.getchildren() for c in ccc: if c.tag=="{http://www.w3.org/2000/svg}image": href=c.attrib["{http://www.w3.org/1999/xlink}href"] fp.write(href) img = Image.open(href) width_in_svg=child.attrib['width'] height_in_svg=child.attrib['height'] elif child.tag=="{http://www.w3.org/2000/svg}image": href=child.attrib["{http://www.w3.org/1999/xlink}href"] width_in_svg=child.attrib['width'] height_in_svg=child.attrib['height'] if "file://" in href: href=href[7:] fp.write(href+"\n") img = Image.open(href).convert("RGB") width=-1 height=-1 if img!=None: imagesize = img.size width=img.size[0] height=img.size[1] fp.write("imageSize="+str(imagesize)) trans = self.getGlobalTransform(parentGroup) invtrans = None if trans: invtrans = self.invertTransform(trans) #}}} #{{{ Recovery of the selected objects pts = [] nodes = [] seeds = [] fp.write('num:'+str(len(self.options.ids))+'\n') for id in self.options.ids: node = self.selected[id] nodes.append(node) if(node.tag=="{http://www.w3.org/2000/svg}path"):#pathだった場合 #パスの頂点座標を取得 points = cubicsuperpath.parsePath(node.get('d')) fp.write(str(points)+"\n") for p in points[0]: pt=[p[1][0],p[1][1]] if trans: simpletransform.applyTransformToPoint(trans, pt) pts.append(Point(pt[0], pt[1])) seeds.append(Point(p[1][0], p[1][1])) else:#その他の図形の場合 bbox = simpletransform.computeBBox([node]) if bbox: cx = 0.5 * (bbox[0] + bbox[1]) cy = 0.5 * (bbox[2] + bbox[3]) pt = [cx, cy] if trans: simpletransform.applyTransformToPoint(trans, pt) pts.append(Point(pt[0], pt[1])) seeds.append(Point(cx, cy)) pts.sort() seeds.sort() fp.write("*******sorted!***********"+str(len(seeds))+"\n") #}}} #{{{ Creation of groups to store the result # Delaunay groupDelaunay = inkex.etree.SubElement(parentGroup, inkex.addNS('g', 'svg')) groupDelaunay.set(inkex.addNS('label', 'inkscape'), 'Delaunay') #}}} scale_x=float(width_in_svg)/float(width) scale_y=float(height_in_svg)/float(height) fp.write('width='+str(width)+', height='+str(height)+'\n') fp.write('scale_x='+str(scale_x)+', scale_y='+str(scale_y)+'\n') #{{{ Voronoi diagram generation triangles = voronoi.computeDelaunayTriangulation(seeds) for triangle in triangles: p1 = seeds[triangle[0]] p2 = seeds[triangle[1]] p3 = seeds[triangle[2]] cmds = [['M', [p1.x, p1.y]], ['L', [p2.x, p2.y]], ['L', [p3.x, p3.y]], ['Z', []]] path = inkex.etree.Element(inkex.addNS('path', 'svg')) path.set('d', simplepath.formatPath(cmds)) middleX=(p1.x+p2.x+p3.x)/3.0/scale_x middleY=(p1.y+p2.y+p3.y)/3.0/scale_y fp.write("x:"+str(middleX)+" y:"+str(middleY)+"\n") if img!=None and imagesize[0]>middleX and imagesize[1]>middleY and middleX>=0 and middleY>=0: r,g,b = img.getpixel((middleX,middleY)) facestyle["fill"]=simplestyle.formatColor3i(r,g,b) else: facestyle["fill"]="black" path.set('style', simplestyle.formatStyle(facestyle)) groupDelaunay.append(path) fp.close()