Exemple #1
0
    def test_point(self, p, error=None, interpolation=None, error_norm_order=2, update_improvement_map=False):
        # Calculate old error
        error_old = norm(self.interpolation_map() - self.dem, error_norm_order)

        # Append the new coordinates
        p = np.round(p).astype(int)
        points = np.vstack([self.points, [p]])
        values = np.append(self.point_elevations, self.dem_elevation(p[0], p[1]))

        # Retriangulate
        tri_new = triangle.delaunay(points)
        tri_new = mpltri.Triangulation(*points.T, triangles=tri_new)

        # Reinterpolate
        interpolator = mpltri.LinearTriInterpolator(tri_new, values)
        interpolation_new = interpolator(self.yy, self.xx)

        # Calculate new error
        error_new = norm(interpolation_new - self.dem, error_norm_order)

        improvement = error_new - error_old

        if update_improvement_map:
            self.improvement_map[p[1], p[0]] = improvement

        return improvement
 def set_triangles(self):
     points = []
     for ver in self.vertexes:
         points.append(ver.pos[0:2])
     triangles = delaunay(points)
     for tri in triangles:
         self.triangles.extend(self.vertexes[tri[i]].pos for i in xrange(3))
Exemple #3
0
def terrainLOD0(fname, npoints, lowerbound, upperbound, cityModel):
    i = 0
    points = []
    ptdir = {}

    while i < npoints:
        randomx = random.uniform(lowerbound[0], upperbound[0])
        randomy = random.uniform(lowerbound[1], upperbound[1])
        randomz = random.uniform(lowerbound[2], upperbound[2])

        points.append([randomx, randomy, randomz])
        ptdir[i] = [randomx, randomy, randomz]

        i = i + 1

    x, y, origin, n = getxy(points)

    local_coords = []
    sep = []
    for p in points:
        S = np.dot(n, p - origin)
        sep.append(S)
        local_coords.append((np.dot(p - origin, x), np.dot(p - origin, y)))

    tri = triangle.delaunay(local_coords)
    get_TINRelief(cityModel, tri, ptdir, "lod0")
Exemple #4
0
    def triangulation(self, recalculate=False):
        if recalculate or self.triangulation_dirty:
            self._triangulation = triangle.delaunay(self.points)
            self._triangulation = mpltri.Triangulation(*self.points.T,
                                                       triangles=self._triangulation)

        self.triangulation_dirty = False
        return self._triangulation
def heuristic_reconstruction(points: list, filename = None):
    points = np.array(points)

    ax = plt.axes()
    #drawing.plot_and_save(os.path.join(images_folder, filename+"_original.png"), False, ax, vertices=points, vertices_color="g")
    lim = ax.axis()

    deltriangles = triangle.delaunay(points)
    delaunay_edges = []
    for t in deltriangles:
        delaunay_edges.extend(edges_from_triangle(t))

    #try:
    drawing.plot(ax, vertices=points, segments=delaunay_edges)
    drawing.plot_and_save(os.path.join(images_folder, os.path.join("delaunay",filename+"delaunay.eps")),
        True, ax, vertices=points, vertices_color="b")
    ax.axis(lim)


    triangles_length = [perimeter(points, t) for t in deltriangles]
    mean_length = sum(triangles_length)/len(triangles_length)
    std_length = np.std(triangles_length)
    filtered_triangles = [deltriangles[i] for i in range(len(deltriangles)) if triangles_length[i] < (mean_length + 1*std_length)]

    ax = plt.axes()
    drawing.plot_and_save(os.path.join(images_folder, os.path.join("boundary", filename+"_region1std.eps")),
                True, ax, triangles = filtered_triangles, vertices=points, draw_vertices=False)

    #graph initialization
    num_of_triangles = len(filtered_triangles)
    graph = [Node(i) for i in range(num_of_triangles)]
    for node in graph:
        vertices = filtered_triangles[node.id]
        node.neighbors = [index for index in range(num_of_triangles) if len(set(vertices).intersection(filtered_triangles[index])) == 2]
        node.costs = [1.0 for i in node.neighbors]

    connected_one = []
    def append_to(node, connected_one:list):
        connected_one.append(node)

    BFS(graph, 1, append_to, connected_one)


    boundary_triangles = [filtered_triangles[node.id] for node in connected_one if len(node.neighbors) < 3]

    filtered_segments = []
    for t in filtered_triangles:
        filtered_segments.extend(edges_from_triangle(t))
    boundary_segments = [edge for edge in filtered_segments if filtered_segments.count(edge) == 1]
    # print(boundary_segments)

    ax = plt.axes()
    drawing.plot_and_save(os.path.join(images_folder, os.path.join("boundary", filename+"_boundary_triangles1std.eps")),
                True, ax, triangles = boundary_triangles, vertices=points, segments=boundary_segments)

    ax = plt.axes()
    drawing.plot_and_save(os.path.join(images_folder, os.path.join("boundary", filename+"_boundary_triangles1stdstd.eps")),
                True, ax, vertices=points, segments=boundary_segments)
Exemple #6
0
def true_deulunay(points):
    G = nx.Graph()
    for p in points.keys():
        G.add_node(p)
    triangles = triangle.delaunay([locs[x] for x in sorted(locs.keys())])
    for t in triangles:
        G.add_edge(t[0], t[1])
        G.add_edge(t[1], t[2])
        G.add_edge(t[2], t[0])
    return G
Exemple #7
0
def test_easy():
    points = [[1.0, 2.0, 2.0, 5.0, 9.0, 10.0, -1.0],
              [1.0, 1.0, 2.0, 7.0, 11.0, 11.0, 8.0]]
    d = triangle.delaunay([(points[0][i], points[1][i])
                           for i in range(len(points[0]))])
    diagram = get_persistence([[points[0][i], points[1][i]]
                               for i in range(len(points[0]))]).get_diagram()
    print(diagram)
    pyplot.scatter(points[0], points[1], marker='o')
    pyplot.triplot(points[0], points[1], d)
    pyplot.show()
Exemple #8
0
def test_hard():
    points = generators.poisson.poisson_homogeneous_point_process(1, 50)
    d = triangle.delaunay(points)
    diagram = get_persistence(points).get_diagram()
    pyplot.figure(1)
    pyplot.triplot([points[i][0] for i in range(len(points))],
                   [points[i][1] for i in range(len(points))], d)
    pyplot.figure(2)
    pyplot.scatter([diagram[i][0] for i in range(len(diagram))],
                   [diagram[i][1] for i in range(len(diagram))],
                   marker='o')
    pyplot.show()
Exemple #9
0
def test_delaunay():
    pts = [[0, 0], [0, 1], [0.5, 0.5], [1, 1], [1, 0]]
    tri = delaunay(pts)
    assert np.allclose(
        tri,
        [
            [1, 0, 2],
            [2, 4, 3],
            [4, 2, 0],
            [2, 3, 1],
        ],
    )
    def auto_plane(self):
        indices_split = self.indices_split[np.nonzero(self.all_con)]
        data_gnd = self.ptCLoudData[np.nonzero(self.all_con)]
        plane_split = self.plane_split

        for i in range(1, len(plane_split)):
            sel = data_gnd[np.nonzero(indices_split == i)]
            if len(sel) < 3:
                continue
            pca = PCA(n_components=2)
            data_transfer = pca.fit_transform(sel['a_position'])
            tri = np.array(triangle.delaunay(data_transfer), dtype=np.uint32)
            self.all_plane.append({'data': sel, 'tri': tri})
Exemple #11
0
def delaunayMap(points, imageSize = (0, 0)):
    """Return a GeoMap containing a Delaunay Triangulation of the given
    points."""

    if len(points) < 3:
        raise ValueError, \
              "cannot compute Delaunay Triangulation of less than three points"

    if triangle:
        nodePositions, edges = triangle.delaunay(points)
        sigma = None
    else:
        nodePositions, edges, sigma = geomap.delaunay(points)
    return _delaunayMapFromData(nodePositions, edges, imageSize,
                                sigma)
Exemple #12
0
def delaunayMap(points, imageSize = (0, 0)):
    """Return a GeoMap containing a Delaunay Triangulation of the given
    points."""

    if len(points) < 3:
        raise ValueError, \
              "cannot compute Delaunay Triangulation of less than three points"
    
    if triangle:
        nodePositions, edges = triangle.delaunay(points)
        sigma = None
    else:
        nodePositions, edges, sigma = geomap.delaunay(points)
    return _delaunayMapFromData(nodePositions, edges, imageSize,
                                sigma)
def NNcrust(points: list, filename = None)-> list:
    points = np.array(points)

    ax = plt.axes()
    drawing.plot_and_save(os.path.join(images_folder, filename+"_original.png"), False, ax, vertices=points, vertices_color="g")
    lim = ax.axis()

    triangles = triangle.delaunay(points)
    delaunay_edges = []
    for t in triangles:
        delaunay_edges.extend(edges_from_triangle(t))

    rec_edges = set([])
    for i in range(len(points)):
        edges_with_p = [edge for edge in delaunay_edges if i in edge]
        if edges_with_p:
            costs = [distance(points, edge) for edge in edges_with_p]
            min_index = costs.index(min(costs))
            pq = edges_with_p[min_index]
            rec_edges.add(pq)

        ps_candidates = [edge for edge in edges_with_p if
            cos_angle(points[i], points[pq[0] if pq[0] != i else pq[1]], points[edge[0] if edge[0] != i else edge[1]]) < 0]
        if ps_candidates:
            costs = [distance(points, edge) for edge in ps_candidates]
            min_index = costs.index(min(costs))
            ps = ps_candidates[min_index]
            rec_edges.add(ps)

    # rec_edges = [e for e in delaunay_edges if ((e[0] < len(points)) and (e[1] < len(points)))]
    try:
        drawing.plot(ax, vertices=points, edges=delaunay_edges, segments=rec_edges)
        drawing.plot_and_save(os.path.join(images_folder, os.path.join("delaunay",filename+"delaunay.png")),
            True, ax, vertices=points, vertices_color="b")
        ax.axis(lim)
    except Exception as e:
        print("Could not draw delaunay diagram. Please, check if you have the correct directory")


    #final reconstruction
    ax = plt.axes()
    drawing.plot_and_save(os.path.join(images_folder, filename+"_reconstruction.png"),
                            True, ax, vertices=points, segments=rec_edges, draw_vertices=False)
    # print(points)
    # print(rec_edges)
    ordered_points = []

    return ordered_points
Exemple #14
0
def convert_point(point_set, point_on_plane, axis):
    tmp = []
    u = []
    v = []
    z = []
    for i in point_set:
        z.append(i[2])
        tmp = [i[x] - point_on_plane[x] for x in range(3)]
        tmp_u = np.dot(tmp, axis[0])
        tmp_v = np.dot(tmp, axis[1])
        u.append(tmp_u)
        v.append(tmp_v)

    points = np.column_stack((u, v))

    tri = triangle.delaunay(points)
    return tri
    def auto_plane_gnd(self):
        # TODO the condition is no need
        indices_split_gnd = self.indices_split[np.nonzero(self.gnd_con)]
        data_gnd = self.ptCLoudData[np.nonzero(self.gnd_con)]
        plane_split = self.plane_split

        for i in range(1, len(plane_split)):
            plane = plane_split[i]
            vec = (plane['nx'], plane['ny'], plane['nz'])
            angle_diff = base_process.angle_between(vec, (0, 0, -1))
            if angle_diff < 0.3 or True:
                sel = data_gnd[np.nonzero(indices_split_gnd == i)]
                if len(sel) < 3:
                    continue
                pca = PCA(n_components=2)
                data_transfer = pca.fit_transform(sel['a_position'])
                tri = np.array(triangle.delaunay(data_transfer), dtype=np.uint32)
                self.gnd_plane.append({'data': sel, 'tri': tri})
Exemple #16
0
def crust(points: list, filename = None)-> list:
    points = np.array(points)

    ax = plt.axes()
    drawing.plot_and_save(os.path.join(images_folder, filename+"_original.png"), False, ax, vertices=points, vertices_color="g")
    lim = ax.axis()

    vertices, edges, ray_origins, ray_directions = triangle.voronoi(points)
    try:
        drawing.plot_and_save(os.path.join(images_folder, os.path.join("voronoi", filename+"_voronoi.png")),
         False, ax, vertices=vertices, edges=edges, ray_origins=ray_origins, ray_directions=ray_directions)
        ax.axis(lim)
    except Exception as e:
        print("Could not draw voronoi diagram. Please, check if you have the correct directory")

    extended_points = np.concatenate((points, vertices))

    triangles = triangle.delaunay(extended_points)
    delaunay_edges = []
    for t in triangles:
        delaunay_edges.extend(edges_from_triangle(t))

    rec_edges = [e for e in delaunay_edges if ((e[0] < len(points)) and (e[1] < len(points)))]
    try:
        drawing.plot(ax, vertices=extended_points, edges=delaunay_edges, segments=rec_edges)
        drawing.plot_and_save(os.path.join(images_folder, os.path.join("delaunay",filename+"delaunay.png")),
            True, ax, vertices=points, vertices_color="b")
        ax.axis(lim)
    except Exception as e:
        print("Could not draw delaunay diagram. Please, check if you have the correct directory")


    #final reconstruction
    ax = plt.axes()
    drawing.plot_and_save(os.path.join(images_folder, filename+"_reconstruction.png"),
                            True, ax, vertices=points, segments=rec_edges, draw_vertices=False)
    # print(points)
    # print(rec_edges)
    ordered_points = []

    return ordered_points
Exemple #17
0
def gen_ground_triangles(ground, origin, x, y):
    faces = []
    localGround = []
    for p in ground:
        localGround.append((np.dot(p - origin, x), np.dot(p - origin, y)))
    tr = triangle.delaunay(localGround)
    for t in tr:
        s = [ground[t[0]], ground[t[1]], ground[t[2]]]
        sp = Polygon(s)
        sp = geometry.polygon.orient(sp, 1)
        faces.append(sp)

#    ground1 = [ground[0],ground[1],ground[2],ground[0]]
#    ground2 =[ground[2],ground[3],ground[0],ground[2]]
#    g1 = Polygon(ground1)
#    g1 = geometry.polygon.orient(g1, 1)
#    g2 = Polygon(ground2)
#    g2 = geometry.polygon.orient(g2, 1)

#    faces.append(g1)
#    faces.append(g2)

    return faces
Exemple #18
0
def setup(POLYGON_COUNT=4096,
          SCREEN_WIDTH=1152,
          SCREEN_HEIGHT=900,
          HUD_SIZE=32 * 9,
          main_island_shape_seed=800,
          small_island_shape_seed=300,
          improve_points=False,
          triangles=False):
    OFFSETX = int(0.04 * SCREEN_WIDTH)
    OFFSETY = int(0.05 * SCREEN_HEIGHT)
    polygons = []
    SECTION_SIZE = POLYGON_COUNT // 80

    # this is for game use
    display_size = (SCREEN_WIDTH + HUD_SIZE, SCREEN_HEIGHT)

    # centre of the effective screen for map generation/display
    centre = tuple(
        map(int, ((SCREEN_WIDTH + 0.4 * OFFSETX) / 2,
                  (SCREEN_HEIGHT + 0.5 * OFFSETY) / 2)))

    # euclidean distance from diagonal map corner with a slight offset
    # larger max_dist will affect the size of the main island
    max_dist = int((centre[0]**2 + centre[1]**2)**.5) - int(6.6 * OFFSETX)

    # these are the polygon centres
    generator_sites = []
    for i in range(POLYGON_COUNT):
        while True:
            p = Point(random.randrange(-OFFSETX, SCREEN_WIDTH + OFFSETX),
                      random.randrange(-OFFSETY, SCREEN_HEIGHT + OFFSETY), i)
            if not [i for i in generator_sites if i.x == p.x and i.y == p.y]:
                break
        generator_sites.append(p)

    # delaunay triangles provide co-ordinates of polygon vertices
    print("Generating delaunay triangles...")
    tris = triangle.delaunay(
        [poly_centre.get_cords() for poly_centre in generator_sites])
    Triangles = [
        Triangle(generator_sites[i[0]], generator_sites[i[1]],
                 generator_sites[i[2]]) for i in tris
    ]

    # these are class based functions to retain a random seed. Useful for map generation
    # look at the Island Class for more information
    print("Generating island shapes...")
    island_shape = Island(main_island_shape_seed)
    smaller_island = Island(small_island_shape_seed)

    # polygons are the polygon objects, poly_sites is a useful look-up dict
    # for x,y co-ordinates matching a polygon
    print("Generating polygons...")
    if triangles:
        polygons, poly_sites = __alt_polygon_generator(Triangles, centre,
                                                       max_dist, island_shape,
                                                       smaller_island)
    else:
        polygons, poly_sites = __polygon_generator(generator_sites, Triangles,
                                                   centre, max_dist,
                                                   island_shape,
                                                   smaller_island)

    if improve_points:
        generator_sites = []
        print("Improving points...")
        for counter, p in enumerate(polygons):
            x, y = p.centroid()
            generator_sites.append(Point(x, y, counter))

        tris = triangle.delaunay(
            [poly_centre.get_cords() for poly_centre in generator_sites])
        Triangles = [
            Triangle(generator_sites[i[0]], generator_sites[i[1]],
                     generator_sites[i[2]]) for i in tris
        ]
        if triangles:
            polygons, poly_sites = __alt_polygon_generator(
                Triangles, centre, max_dist, island_shape, smaller_island)
        else:
            polygons, poly_sites = __polygon_generator(generator_sites,
                                                       Triangles, centre,
                                                       max_dist, island_shape,
                                                       smaller_island)
    ## this is arbitrary and can be changed however it appeared to work reasonably well
    # I've tried higher and lower.
    mount_count = POLYGON_COUNT // 200

    # this is the main generator function and will determine most of the map terrain
    # see relevant function for more details
    print("Generating mountains, rivers and city locations...")
    river_list, city_sites, regions = _determine_terrain(
        mount_count, poly_sites, polygons, centre, max_dist)

    print("Generating roads...")
    road_list = _make_roads(city_sites)

    print("")
    print("Map created...")
    print("Key data:")
    print("mountains = ", mount_count)
    print("rivers = ", len(river_list))
    print("cities = ", len(city_sites))
    print("roads = ", len(road_list))

    # return data and render objects
    return display_size, polygons, poly_sites, river_list, city_sites, road_list, regions
Exemple #19
0
                            continue
                        texture_data = np.zeros(
                            (texture_len),
                            dtype=[('a_position', np.float32, 3),
                                   ('a_color', np.float32, 3)])
                        texture_data['a_color'] = np.array(texture_color)
                        texture_data['a_position'] = np.array(texture_xyz)

                        # pca = PCA(n_components=2)
                        # data_transfer = pca.fit_transform(texture_data['a_position'])
                        #data_transfer = texture_data['a_position'][:, 0:2]
                        #texture_tri = np.array(triangle.delaunay(data_transfer), dtype=np.uint32)
                        pca = PCA(n_components=2)
                        data_transfer = pca.fit_transform(
                            np.array(texture_xyz_3d))
                        tri = np.array(triangle.delaunay(data_transfer),
                                       dtype=np.uint32)
                        texture_data['a_position'][:, 0] = texture_data[
                            'a_position'][:, 0] / 256.0 - 1.0
                        texture_data['a_position'][:, 1] = -(
                            texture_data['a_position'][:, 1] / 128.0 - 1.0)

                        programTexture = glumpy_setting.ProgramTexture(
                            data=texture_data, name='ProgramTexture', tri=tri)
                        programTexture_set.append(programTexture)
                    #break
                print(rrr)
                #scipy.misc.imshow(syn_pano)

        if needVisual:
            programSV3DRegion = glumpy_setting.ProgramSV3DRegion(
            data = np.concatenate((data, sv3D.ptCLoudData), axis=0)

        index += 1
        if index > 0:
            break
        #break

gpyWindow = glumpy_setting.GpyWindow()

programSV3DRegion = glumpy_setting.ProgramSV3DRegion(
    data=data, name=None, point_size=1, anchor_matrix=anchor_matrix_whole)
programSV3DRegion.apply_anchor()
#gpyWindow.add_program(programSV3DRegion)

data = programSV3DRegion.data
tri = np.array(triangle.delaunay(data['a_position'][:, 0:2]), dtype=np.uint32)
programGround = glumpy_setting.ProgramPlane(data=data,
                                            name=str(index),
                                            face=tri)
gpyWindow.add_program(programGround)
"""
ALL PLY EXPORT IN HERE
"""

data = programSV3DRegion.data
data['a_color'] *= 255
data['a_color'].astype(int)

xyzzz = np.zeros(len(data),
                 dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('red', 'u1'),
                        ('green', 'u1'), ('blue', 'u1')])
def triangulate_triangle(nodes, randstream):
    import triangle
    data = triangle.delaunay(nodes)
    return data
Exemple #22
0
    d = triangle.delaunay(points)
    diagram = get_persistence(points).get_diagram()
    pyplot.figure(1)
    pyplot.triplot([points[i][0] for i in range(len(points))],
                   [points[i][1] for i in range(len(points))], d)
    pyplot.figure(2)
    pyplot.scatter([diagram[i][0] for i in range(len(diagram))],
                   [diagram[i][1] for i in range(len(diagram))],
                   marker='o')
    pyplot.show()


tim = []
for i in range(2):
    points = generators.poisson.poisson_homogeneous_point_process(1, 5000)
    d = triangle.delaunay(points)
    pers = get_persistence(points)
    #pyplot.figure(1)
    pyplot.plot(
        range(len(pers.numOfComponents)),
        pers.numOfComponents,
        '-b',
        range(len(pers.numOfBigComponents)),
        pers.numOfBigComponents,
        '-r',
        range(len(pers.numOfCycles)),
        pers.numOfCycles,
        '-g',
    )
    #pyplot.show()
    b_1 = max(pers.numOfCycles)
Exemple #23
0
    def from_points(cls, x, y):
        """
        Построение фильтрации Чеха по набору точек из R^2.
        :param points:
        :return:
        """
        if len(x) != len(y):
            raise RuntimeError('Длины x и y должны совпадать!')
        f = Filtration()
        f.vertNum = len(x)

        # Индексирование вершин, рёбер и треугольников
        f.vertices = [
            triangulation.vert.Vert(idx, x[idx], y[idx])
            for idx in range(f.vertNum)
        ]
        f.incidEdgesToVertices = [[] for i in range(f.vertNum)]
        f.incidTrianglesToVertices = [[] for i in range(f.vertNum)]

        tr = triangle.delaunay(np.transpose([x, y]))
        f.trNum = len(tr)

        f.triangles = [
            triangulation.triang.Triang(idx, tr[idx][0], tr[idx][1],
                                        tr[idx][2]) for idx in range(f.trNum)
        ]
        f.incidEdgesToTriangles = [[] for i in range(f.trNum)]

        # Индексируем рёбра для быстрого поиска
        edges_idx = dict()

        idx = 0

        # внешность не учитываем
        for triIdx in range(f.trNum):
            tr = f.triangles[triIdx]
            if not edges_idx.get((tr.v(0), tr.v(1))):
                f.edges.append(triangulation.edge.Edge(idx, tr.v(0), tr.v(1)))
                edges_idx[(tr.v(0), tr.v(1))] = True
                edges_idx[(tr.v(1), tr.v(0))] = True
                idx += 1
            if not edges_idx.get((tr.v(0), tr.v(2))):
                f.edges.append(triangulation.edge.Edge(idx, tr.v(0), tr.v(2)))
                edges_idx[(tr.v(0), tr.v(2))] = True
                edges_idx[(tr.v(2), tr.v(0))] = True
                idx += 1
            if not edges_idx.get((tr.v(1), tr.v(2))):
                f.edges.append(triangulation.edge.Edge(idx, tr.v(1), tr.v(2)))
                edges_idx[(tr.v(1), tr.v(2))] = True
                edges_idx[(tr.v(2), tr.v(1))] = True
                idx += 1

        f.edgeNum = len(f.edges)
        f.incidTrianglesToEdges = [[] for i in range(f.edgeNum)]

        # Инициализация списков инцидентных рёбер для вершин
        # Пробегаем все ребра, каждое приписываем двум его вершинам.
        # Результат: массив, индексы которого - глоальные номера точек,
        # в i-ой ячейке - список индексов ребер, инцедентных i-ой вершине.
        for idx in range(f.edgeNum):
            v0 = f.edges[idx].v(0)
            v1 = f.edges[idx].v(1)
            f.incidEdgesToVertices[v0].append(idx)
            f.incidEdgesToVertices[v1].append(idx)

        # Инициализация списков инцидентных треугольников для вершин
        # Пробегаем все треугольники, каждый записываем в 3 списка,
        # соответствующих вершинам этого треугольника.
        # Результат: массив, индексы которого - глоальные номера точек,
        # в i-й ячейке - список индексов треугольников, содержащих i-ую вершину.
        for idx in range(f.trNum):
            f.incidTrianglesToVertices[f.triangles[idx].v(0)].append(idx)
            f.incidTrianglesToVertices[f.triangles[idx].v(1)].append(idx)
            f.incidTrianglesToVertices[f.triangles[idx].v(2)].append(idx)

        # Инициализация списков инцидентных рёбер для треугольников
        # Пробегаем все треугольники
        for i in range(f.trNum):
            # Количество ребер, инцидентных вершине A треугольника i.
            iAEdgesCount = len(f.incidEdgesToVertices[f.triangles[i].v(0)])
            # Для i-ого треугольника просматриваем список инцедентных ребер вершины A.
            # Если текущее (j-ое) ребро равно ребру AB или AC i-ого треугольника,
            # добавляем это ребро в список ребер, инцедентных i-ому треугольнику.
            for j in range(iAEdgesCount):
                # Глобальный индекс j-ого ребра инцидентного вершине A i-ого треугольника.
                iAj = f.incidEdgesToVertices[f.triangles[i].v(0)][j]
                if (f.edges[iAj].equals(f.triangles[i].v(0),
                                        f.triangles[i].v(1))
                        or f.edges[iAj].equals(f.triangles[i].v(0),
                                               f.triangles[i].v(2))):
                    f.incidEdgesToTriangles[i].append(iAj)
            # Количество ребер, инцидентных вершине B треугольника i.
            iBEdgesCount = len(f.incidEdgesToVertices[f.triangles[i].v(1)])
            # Для i-ого треугольника просматриваем список инцедентных ребер вершины B.
            # Если текущее (j-ое) ребро равно ребру BC i-ого треугольника,
            # добавляем это ребро в список ребер, инцедентных i-ому треугольнику.
            for j in range(iBEdgesCount):
                # Глобальный индекс j-ого ребра инцидентного вершине B i-ого треугольника.
                iBj = f.incidEdgesToVertices[f.triangles[i].v(1)][j]
                if f.edges[iBj].equals(f.triangles[i].v(1),
                                       f.triangles[i].v(2)):
                    f.incidEdgesToTriangles[i].append(iBj)

        # Инициализация списка инцидентных треугольников для рёбер
        # Пробегаем все треугольники, каждый записываем в 3 списка,
        # соответствующих ребрам этого треугольника.
        # Результат: массив, индексы которого - глобальные номера ребер,
        # в i-ой ячейке - список индексов треугольников, инцедентных i-ому ребру.
        for i in range(f.trNum):
            f.incidTrianglesToEdges[f.incidEdgesToTriangles[i][0]].append(i)
            f.incidTrianglesToEdges[f.incidEdgesToTriangles[i][1]].append(i)
            f.incidTrianglesToEdges[f.incidEdgesToTriangles[i][2]].append(i)

        # Инициализация списка граничных рёбер
        for edge_idx in range(f.edgeNum):
            if len(f.incidTrianglesToEdges[edge_idx]) == 1:
                f.boardEdges.append(edge_idx)

        # Инициализация списка граничных вершин
        for edge_idx in f.boardEdges:
            v0 = f.edges[edge_idx].v(0)
            v1 = f.edges[edge_idx].v(1)
            if v0 not in f.boardVertices:
                f.boardVertices.append(v0)
            if v1 not in f.boardVertices:
                f.boardVertices.append(v1)

        # Add outer face to the triangulation
        outIdx = f.trNum
        out = triangulation.triang.Out(outIdx, f.boardVertices)
        f.triangles.append(out)
        f.incidEdgesToTriangles.append(f.boardEdges)

        for vert_idx in f.boardVertices:
            f.incidTrianglesToVertices[vert_idx].append(outIdx)

        for edge_idx in f.boardEdges:
            f.incidTrianglesToEdges[edge_idx].append(outIdx)

        f.trNum += 1  # учитываем внешность

        f.simpNum = f.vertNum + f.edgeNum + f.trNum

        # Добавление вершин, ребер, треугольников, внешности
        for i in range(f.vertNum):
            f.simplexes.append(f.vertices[i])
        for i in range(f.edgeNum):
            f.simplexes.append(f.edges[i])
        for i in range(f.trNum):
            f.simplexes.append(f.triangles[i])

        # Инициализация времен появления
        for s in f.simplexes:
            if s.dim == 0:
                s.appTime = 0
            elif s.dim == 1:
                length = triangulation.util.dist(f.vertices[s.v(0)],
                                                 f.vertices[s.v(1)])
                s.appTime = length / 2
            elif s.dim == 2:
                len_a = triangulation.util.dist(f.vertices[s.v(0)],
                                                f.vertices[s.v(1)])
                len_b = triangulation.util.dist(f.vertices[s.v(0)],
                                                f.vertices[s.v(2)])
                len_c = triangulation.util.dist(f.vertices[s.v(1)],
                                                f.vertices[s.v(2)])
                if triangulation.util.is_obtuse(len_a, len_b, len_c):
                    s.appTime = max([len_a, len_b, len_c]) / 2
                else:
                    s.appTime = triangulation.util.outer_radius(
                        f.vertices[s.v(0)], f.vertices[s.v(1)],
                        f.vertices[s.v(2)])
        f.simplexes[-1].appTime = max(
            [f.triangles[i].appTime for i in range(f.trNum - 1)]) + 1

        # Сортировка списка симплексов по времени появления
        f.sort_simplexes()

        # Инициализация индексов фильтрации симплексов
        for i in range(f.simpNum):
            f.simplexes[i].filtInd = i

        return f
Exemple #24
0
                        if crossPhase:
                            if len(texture_xyz_3d_back_right) >= 3:
                                texture_data = np.zeros(
                                    (texture_len_back_right),
                                    dtype=[('a_position', np.float32, 3),
                                           ('a_color', np.float32, 3)])
                                texture_data['a_color'] = np.array(
                                    texture_color_back_right)
                                texture_data['a_position'] = np.array(
                                    texture_xyz_back_right)

                                pca = PCA(n_components=2)
                                data_transfer = pca.fit_transform(
                                    np.array(texture_xyz_3d_back_right))
                                tri = np.array(
                                    triangle.delaunay(data_transfer),
                                    dtype=np.uint32)
                                texture_data[
                                    'a_position'][:, 0] = texture_data[
                                        'a_position'][:, 0] / float(
                                            texture_height) - 1.0
                                texture_data['a_position'][:, 1] = -(
                                    texture_data['a_position'][:, 1] /
                                    float(texture_height) * 2.0 - 1.0)

                                programTexture = glumpy_setting.ProgramTexture(
                                    data=texture_data,
                                    name='ProgramTexture',
                                    tri=tri)
                                programTexture_set.append(programTexture)
Exemple #25
0
gpyWindow = glumpy_setting.GpyWindow()

#programSV3DRegion = glumpy_setting.ProgramSV3DRegion(data=data, name=None, point_size=1, anchor_matrix=anchor_matrix_whole)
#programSV3DRegion.apply_anchor()
#gpyWindow.add_program(programSV3DRegion)

programSV3DRegion = glumpy_setting.ProgramSV3DRegion(
    data=data_gnd, name=None, point_size=1, anchor_matrix=anchor_matrix_whole)
programSV3DRegion.apply_anchor()
gpyWindow.add_program(programSV3DRegion)

#programSV3DRegion = glumpy_setting.ProgramSV3DRegion(data=data_gnd_grid, name=None, point_size=1, anchor_matrix=anchor_matrix_whole, alpha=0)
#programSV3DRegion.apply_anchor()
#gpyWindow.add_program(programSV3DRegion)
"""
Triangle
"""
tri = np.array(triangle.delaunay(data_gnd['a_position'][:, 0:2]),
               dtype=np.uint32)
#data_gnd_grid['a_position'] = base_process.sv3d_apply_m4(data=data_gnd_grid['a_position'], m4=np.linalg.inv(anchor_matrix_whole))
#data_gnd['a_position'][:, 2] = 0
programGround = glumpy_setting.ProgramPlane(data=data_gnd,
                                            name=str(index),
                                            face=tri)
gpyWindow.add_program(programGround)

#programAxis = glumpy_setting.ProgramAxis(line_length=5)
#gpyWindow.add_program(programAxis)

gpyWindow.run()
def triangulate_triangle(nodes, randstream):
	import triangle
	data = triangle.delaunay(nodes)
	return data
Exemple #27
0
import matplotlib.pyplot as plt
import numpy as np

import triangle as tr

pts = np.array([[0, 0], [0, 1], [.5, .5], [1, 1], [1, 0]])
tri = tr.delaunay(pts)

A = dict(vertices=pts)
B = dict(vertices=pts, triangles=tri)
tr.compare(plt, A, B)
plt.show()
Exemple #28
0
def main():
    buildings_path = "by_get_shp/by_get"  ##read points from datahandler
    propertys_path = "ay_get_shp/ay_get"
    las_path = "datafromndr/norrkoping.las"

    #points = readPointsFromFile("PolygonPoints.txt") # read strykjarnet from file
    #points = removeOutliers(points, mode='sor', max=2)
    #points = [points]

    data_handler = DataHandler(buildings_path, propertys_path, las_path)
    bfps, points, solids, property_area, mbb, top_dogs = data_handler.get_slice_from_property(
        1592
    )  #Djupet 1593 #Diket 1592 1375 1343 1588 taet data: 1015 843 tre nivaer: 1594

    points = [points[i] for i in range(len(points)) if bfps[i].id in top_dogs]
    points = [points[0]]

    offset = np.mean(property_area.points, 0)
    for p in points:
        p[:, 0:2] -= offset

    rg = SunRegionGrowing()
    regions = rg.getMultiRegions(points)
    planes = []

    #fig = plt.figure()
    #ax = fig.add_subplot(111)

    f = open('myfile.csv', 'w')

    cs_fe = CarlosSantosFeatureExtraction()

    ax = a3.Axes3D(pl.figure())
    for region in regions[0]:  # project points to planes

        planeq = getPlaneLSQ(points[0][region])
        csr = cs_fe.extractFeature(points[0][region], planeq)

        planes.append(planeq)
        hull = np.array(csh.concaveHull(points[0][region][:, 0:2], 100))
        #for p in hull:
        #    p += offset
        hull0 = hull
        hull = np.hstack((hull, hull[:, 0:1]))
        hull = elevatePointsToPlane(hull, planeq)

        for point in hull:
            x, y, z = point
            f.write(str(x) + ",")
            f.write(str(y) + ",")
            f.write(str(z) + "\n")

        f.write("\n")
        tri = a3.art3d.Poly3DCollection([hull])
        vtx = sp.rand(4, 3)
        #tri = a3.art3d.Poly3DCollection([vtx])
        tri.set_color(colors.rgb2hex(sp.rand(3)))
        tri.set_edgecolor('k')
        #ax.add_collection3d(tri)

        #gör tianglelist av 2d hullet -> använd sedan 3d hullet!
        trianglelist = triangle.delaunay(hull0)

        for tri_ids in trianglelist:
            tri = a3.art3d.Poly3DCollection([hull[tri_ids]])  #3d hull
            tri.set_color(colors.rgb2hex(sp.rand(3)))
            tri.set_edgecolor('k')
            ax.add_collection3d(tri)

        for i in range(len(hull)):
            p0 = hull[i]
            p0down = np.array([p0[0], p0[1], 0])
            next = i + 1
            if next == len(hull):
                next = 0
            p1 = hull[next]
            p1down = np.array([p1[0], p1[1], 0])

            tri = a3.art3d.Poly3DCollection([[p0, p0down, p1down]])

            tri.set_color('b')
            tri.set_edgecolor('k')
            ax.add_collection3d(tri)

            tri = a3.art3d.Poly3DCollection([[p0, p1down, p1]])

            tri.set_color('b')
            tri.set_edgecolor('k')
            ax.add_collection3d(tri)

        x = 10

    f.close()

    ax.view_init(elev=39, azim=-55)
    ax.set_xlim3d(-30, 30)
    ax.set_ylim3d(-30, 30)
    ax.set_zlim3d(0, 60)
    pl.show()
Exemple #29
0
            data = np.concatenate((data, sv3D.ptCLoudData), axis=0)

        index += 1
        if index > 0:
            break
        #break


gpyWindow = glumpy_setting.GpyWindow()

programSV3DRegion = glumpy_setting.ProgramSV3DRegion(data=data, name=None, point_size=1, anchor_matrix=anchor_matrix_whole)
programSV3DRegion.apply_anchor()
#gpyWindow.add_program(programSV3DRegion)

data = programSV3DRegion.data
tri = np.array(triangle.delaunay(data['a_position'][:, 0:2]), dtype=np.uint32)
programGround = glumpy_setting.ProgramPlane(data=data, name=str(index), face=tri)
gpyWindow.add_program(programGround)

"""
ALL PLY EXPORT IN HERE
"""

data = programSV3DRegion.data
data['a_color'] *= 255
data['a_color'].astype(int)

xyzzz = np.zeros(len(data), dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')])
xyzzz['x'] = data['a_position'][:, 0]
xyzzz['y'] = data['a_position'][:, 1]
xyzzz['z'] = data['a_position'][:, 2]
Exemple #30
0
gm = geomap.GeoMap(points, [], Size2D(11, 11))

showMapStats(gm)

# import mapdisplay
# d = mapdisplay.MapDisplay(gm)

for i in range(1, len(points)):
    assert gm.node(i).position() == points[i]

for node in gm.nodeIter():
    if not node.degree():
        gm.removeIsolatedNode(node)  # check MapDisplay callbacks

import triangle
points, edgeData = triangle.delaunay(points[1:])

edgeTuples = [
    startEnd and (
        startEnd[0],
        startEnd[1],
        #([points[startEnd[0]], points[startEnd[1]]]))
        geomap.Vector2Array([points[startEnd[0]], points[startEnd[1]]]))
    for startEnd in edgeData
]

print "\n- creating Map from delaunay data (%d edges)..." % (len(edgeTuples) -
                                                             1, )
gm = geomap.GeoMap(points, edgeTuples, Size2D(11, 11))

showMapStats(gm)
Exemple #31
0
def gen_vertical_walls(ground, origin, x, y):

    faces = []
    randomh = random.uniform(15.0, upperBound[2])
    side1 = [
        ground[0], ground[1],
        (ground[0][0], ground[0][1], ground[0][2] + randomh),
        (ground[1][0], ground[1][1], ground[1][2] + randomh)
    ]
    localside11 = []
    for p in side1:
        localside11.append((np.dot(p - origin, x), np.dot(p - origin, y)))
    tr = triangle.delaunay(localside11)
    for t in tr:
        s = [side1[t[0]], side1[t[1]], side1[t[2]]]
        sp = Polygon(s)
        sp = geometry.polygon.orient(sp, 1)
        faces.append(sp)

    side2 = [
        ground[1], ground[2],
        (ground[1][0], ground[1][1], ground[1][2] + randomh),
        (ground[2][0], ground[2][1], ground[2][2] + randomh)
    ]
    localside22 = []
    for p in side2:
        localside22.append((np.dot(p - origin, x), np.dot(p - origin, y)))
    tr = triangle.delaunay(localside22)
    for t in tr:
        s = [side2[t[0]], side2[t[1]], side2[t[2]]]
        sp = Polygon(s)
        sp = geometry.polygon.orient(sp, 1)
        faces.append(sp)

    side3 = [
        ground[2], ground[3],
        (ground[2][0], ground[2][1], ground[2][2] + randomh),
        (ground[3][0], ground[3][1], ground[3][2] + randomh)
    ]
    localside33 = []
    for p in side3:
        localside33.append((np.dot(p - origin, x), np.dot(p - origin, y)))
    tr = triangle.delaunay(localside33)
    for t in tr:
        s = [side3[t[0]], side3[t[1]], side3[t[2]]]
        sp = Polygon(s)
        sp = geometry.polygon.orient(sp, 1)
        faces.append(sp)

    side4 = [
        ground[3], ground[0],
        (ground[3][0], ground[3][1], ground[3][2] + randomh),
        (ground[0][0], ground[0][1], ground[0][2] + randomh)
    ]
    localside44 = []
    for p in side4:
        localside44.append((np.dot(p - origin, x), np.dot(p - origin, y)))
    tr = triangle.delaunay(localside44)
    for t in tr:
        s = [side4[t[0]], side4[t[1]], side4[t[2]]]
        sp = Polygon(s)
        sp = geometry.polygon.orient(sp, 1)
        faces.append(sp)

    roof = [(ground[0][0], ground[0][1], ground[0][2] + randomh),
            (ground[1][0], ground[1][1], ground[1][2] + randomh),
            (ground[2][0], ground[2][1], ground[2][2] + randomh),
            (ground[3][0], ground[3][1], ground[3][2] + randomh)]
    localroof = []
    for p in roof:
        localroof.append((np.dot(p - origin, x), np.dot(p - origin, y)))
    tr = triangle.delaunay(localroof)
    for t in tr:
        s = [roof[t[0]], roof[t[1]], roof[t[2]]]
        sp = Polygon(s)
        sp = geometry.polygon.orient(sp, 1)
        faces.append(sp)

    return faces
Exemple #32
0
                    if needTexture:
                        if len(texture_xyz_3d) < 3:
                            rrr.append(plane_idx)
                            continue
                        texture_data = np.zeros((texture_len),
                                                dtype=[('a_position', np.float32, 3), ('a_color', np.float32, 3)])
                        texture_data['a_color'] = np.array(texture_color)
                        texture_data['a_position'] = np.array(texture_xyz)

                        # pca = PCA(n_components=2)
                        # data_transfer = pca.fit_transform(texture_data['a_position'])
                        #data_transfer = texture_data['a_position'][:, 0:2]
                        #texture_tri = np.array(triangle.delaunay(data_transfer), dtype=np.uint32)
                        pca = PCA(n_components=2)
                        data_transfer = pca.fit_transform(np.array(texture_xyz_3d))
                        tri = np.array(triangle.delaunay(data_transfer), dtype=np.uint32)
                        texture_data['a_position'][:, 0] = texture_data['a_position'][:, 0] / 256.0 - 1.0
                        texture_data['a_position'][:, 1] = -(texture_data['a_position'][:, 1] / 128.0 - 1.0)

                        programTexture = glumpy_setting.ProgramTexture(data=texture_data, name='ProgramTexture', tri=tri)
                        programTexture_set.append(programTexture)
                    #break
                #scipy.misc.imshow(syn_pano)

        if needVisual:
            if needPerspective:
                ori_pano = sv3D.panorama / 255.0
                pano_height, pano_width = ori_pano.shape[0], ori_pano.shape[1]  # Actually, this must be 1:2
                perspective_height, perspective_width = int(pano_height / 4), int(pano_width / 4)
                perspective_data = np.zeros((pano_height*pano_width),
                                            dtype=[('a_position', np.float32, 3), ('a_color', np.float32, 3)])
Exemple #33
0
                programSV3D.info_3d_offs()

            sv3D.matrix_offs = programSV3D.u_model
            #gpyWindow.add_program(programSV3D)

            vec3 = np.reshape(sv3D.ptCLoudData['a_position'], (256 * 512, 3))
            vec4 = np.hstack([vec3, np.ones((len(vec3), 1))])
            vec4_mul = np.dot(vec4, sv3D.matrix_offs)
            vec4_out = np.reshape(vec4_mul[:, 0:3], (256, 512, 3))
            #groundPoint_cur = (sv3D.ptCLoudData[vec4_out[:, :, 2] < -2])
            groundPoint_cur['a_position'] = (vec4_out[(sv3D.ptCLoudData['a_position'][:, :, 2] > 2) * (sv3D.ptCLoudData['a_position'][:, :, 0] > 0)])

            if index == 0:
                matrix_offs_whole = sv3D.matrix_offs
                groundPoint = groundPoint_cur
            else:
                groundPoint = np.concatenate((groundPoint, groundPoint_cur), axis=0)

            index += 1

tri = np.array(triangle.delaunay(groundPoint['a_position'][:, 0:2]), dtype=np.uint32)
programGround = glumpy_setting.ProgramPlane(data=groundPoint, name=str(index), face=tri)
#programGround.u_model = matrix_offs_whole
gpyWindow.add_program(programGround)

programAxis = glumpy_setting.ProgramAxis(line_length=5)
gpyWindow.add_program(programAxis)

gpyWindow.run()

                    img_x = int(lng / 360.0 * 512.0)
                    img_y = int(-(lat - 90) / 180.0 * 256.0)
                    syn_pano[img_y, img_x, :] = point['a_color']
                    index_pano[img_y, img_x] = True

                    yo_xyz.append([img_x, img_y, 0])
                    yo_color.append(point['a_color'])
                    yo_len += 1

        show_pano = np.concatenate((ori_pano, syn_pano), axis=1)
        #scipy.misc.imsave('yo.png', syn_pano)
        scipy.misc.imshow(show_pano)

        data = np.zeros((yo_len),
                        dtype=[('a_position', np.float32, 3),
                               ('a_color', np.float32, 3)])
        data['a_color'] = np.array(yo_color)
        data['a_position'] = np.array(yo_xyz)

        pca = PCA(n_components=2)
        data_transfer = pca.fit_transform(data['a_position'])
        tri = np.array(triangle.delaunay(data_transfer), dtype=np.uint32)
        programImage = glumpy_setting.ProgramPlane(data=data,
                                                   name='test',
                                                   face=tri)
        data['a_position'][:, 0] = data['a_position'][:, 0] / 256.0 - 1.0
        data['a_position'][:, 1] = data['a_position'][:, 1] / 128.0 - 1.0

gpyViewWindow = glumpy_setting.GpyViewWindow(data, tri)
gpyViewWindow.run()
Exemple #35
0
gm = geomap.GeoMap(points, [], Size2D(11, 11))

showMapStats(gm)

# import mapdisplay
# d = mapdisplay.MapDisplay(gm)

for i in range(1, len(points)):
    assert gm.node(i).position() == points[i]

for node in gm.nodeIter():
    if not node.degree():
        gm.removeIsolatedNode(node) # check MapDisplay callbacks

import triangle
points, edgeData = triangle.delaunay(points[1:])

edgeTuples = [startEnd and
              (startEnd[0], startEnd[1],
               #([points[startEnd[0]], points[startEnd[1]]]))
              geomap.Vector2Array([points[startEnd[0]], points[startEnd[1]]]))
              for startEnd in edgeData]

print "\n- creating Map from delaunay data (%d edges)..." % (len(edgeTuples)-1, )
gm = geomap.GeoMap(points, edgeTuples, Size2D(11, 11))

showMapStats(gm)

# addPathFromHere("../subpixelWatersheds")
# import mapdisplay
# d = mapdisplay.MapDisplay(gm)