示例#1
0
def show_points_and_skeleton(point_file, skeleton_file):
    ps.init()
    point_xyz = []
    with open(point_file) as f_in:
        for line in f_in:
            xyz_list = line.split(' ')
            point_xyz.append(np.array([float(xyz_list[1]), float(xyz_list[2]), float(xyz_list[3])]))
    points = np.zeros((len(point_xyz), 3))
    for i in range(len(point_xyz)):
        points[i] = point_xyz[i]
    ps.register_point_cloud("points", points)
    ps_points = ps.get_point_cloud("points")
    ps_points.set_radius(0.0015)

    vertex_pos = []
    line_indices = []
    with open(skeleton_file) as f_in:
        for line in f_in:
            temp = line.split(' ')
            if temp[0] == 'v':
                vertex_pos.append(np.array([float(temp[1]), float(temp[2]), float(temp[3])]))
            # if temp[0] == 'l':
            #     line_indices.append(np.array([int(temp[1]) - 1, int(temp[2]) - 1]))
    points = np.array(vertex_pos)
    # edges = np.array(line_indices)
    # skeleton = ps.register_point_cloud("skeleton curve", points, edges)
    skeleton = ps.register_point_cloud("skeleton curve", points)
    skeleton.set_radius(0.005)
    skeleton.set_color((1,0,0))
    ps.set_autoscale_structures(True)
    ps.show()
def show_polyscope(self):
    # Shows a polyscope window (https://polyscope.run/py/) of the current MeshSet, rendering all the meshes contained
    # in it. Requires the polyscope package (pip install polyscope).
    import polyscope
    import numpy

    polyscope.init()
    for m in self:
        is_enabled = m.is_visible()
        if m.is_point_cloud():
            psm = polyscope.register_point_cloud(m.label(),
                                                 m.transformed_vertex_matrix(),
                                                 enabled=is_enabled)
        else:
            psm = polyscope.register_surface_mesh(
                m.label(),
                m.transformed_vertex_matrix(),
                m.face_matrix(),
                enabled=is_enabled)
        if m.has_vertex_color():
            vc = m.vertex_color_matrix()
            vc = numpy.delete(vc, 3, 1)
            psm.add_color_quantity('vertex_color', vc)
        if m.has_vertex_scalar():
            psm.add_scalar_quantity('vertex_scalar', m.vertex_scalar_array())
        if not m.is_point_cloud() and m.has_face_color():
            fc = m.face_color_matrix()
            fc = numpy.delete(fc, 3, 1)
            psm.add_color_quantity('face_color', fc, defined_on='faces')
        if not m.is_point_cloud() and m.has_face_scalar():
            psm.add_scalar_quantity('face_scalar',
                                    m.face_scalar_array(),
                                    defined_on='faces')
    polyscope.show()
示例#3
0
    def __init__(self,
                 points,
                 bbox3d=None,
                 save_path=None,
                 radius=0.0001,
                 point_color=(0.5, 0.5, 0.5),
                 bbox_color=(0, 1, 0),
                 points_in_box_color=(1, 0, 0),
                 rot_axis=2,
                 center_mode='lidar_bottom',
                 mode='xyz'):
        super(Visualizer, self).__init__()
        assert 0 <= rot_axis <= 2

        self.class2color = {
            'pedestrian': (1, 0, 0),
            'car': (0, 0, 1),
            'truck': (0, 0, 1),
            'bus': (0, 0, 1),
            'trailer': (0.0, 0, 0),
            'barrier': (0.0, 0, 0.0),
            'motorcycle': (0, 1, 0),
            'bicycle': (0, 1, 0),
            'traffic_cone': (0, 0, 0),
            'construction_vehicle': (0, 0, 0),
            'background': (0.5, 0.5, 0.5),
            'Unknown': (0, 0, 0),
        }
        self.points_by_class = {c: None for c in self.class2color.keys()}

        points = points[:, :3]
        ps.init()
        ps.remove_all_structures()
        self.bbox_count = 0

        self.radius = radius
        self.point_color = point_color
        self.bbox_color = bbox_color
        self.points_in_box_color = points_in_box_color
        self.rot_axis = rot_axis
        self.center_mode = center_mode
        self.mode = mode
        self.seg_num = 0

        if isinstance(points, torch.Tensor):
            points = points.numpy()
        # draw points
        self.bg_points = points
        self.draw_points(points,
                         'background',
                         point_color=self.point_color,
                         radius=self.radius)

        # draw boxes
        if bbox3d is not None:
            self.draw_bboxes(bbox3d, bbox_color, points_in_box_color, rot_axis,
                             center_mode, mode)
示例#4
0
def show_points_in_obj_file(obj_file):
    ps.init()
    point_xyz = []
    with open(obj_file) as f_in:
        for line in f_in:
            xyz_list = line.split(' ')
            point_xyz.append(np.array([float(xyz_list[1]), float(xyz_list[2]), float(xyz_list[3])]))
    points = np.zeros((len(point_xyz), 3))
    for i in range(len(point_xyz)):
        points[i] = point_xyz[i]
    ps.register_point_cloud("points", points)
    ps_points = ps.get_point_cloud("points")
    ps_points.set_radius(0.0015)
    ps.set_autoscale_structures(True)
    ps.show()
示例#5
0
    def show(self):
        "use polyscope : https://polyscope.run/py/ "

        assert 0, "TODO"
        import polyscope as ps

        ps.init()

        ### Register a point cloud
        # `my_points` is a Nx3 numpy array
        #ps.register_point_cloud("my points", my_points)

        ### Register a mesh
        # `verts` is a Nx3 numpy array of vertex positions
        # `faces` is a Fx3 array of indices, or a nested list
        # ...

        ps.register_surface_mesh("my mesh", verts, faces, smooth_shade=True)

        ps.show()
示例#6
0
def show_skeleton_in_obj_file(obj_file):
    ps.init()
    vertex_pos = []
    line_indices = []
    with open(obj_file) as f_in:
        for line in f_in:
            temp = line.split(' ')
            if temp[0] == 'v':
                vertex_pos.append(np.array([float(temp[1]), float(temp[2]), float(temp[3])]))
            if temp[0] == 'l':
                line_indices.append(np.array([int(temp[1]) - 1, int(temp[2]) - 1]))
    points = np.array(vertex_pos)
    edges = np.array(line_indices)
    skeleton = ps.register_curve_network("skeleton curve", points, edges)
    point_cloud = ps.register_point_cloud("point cloud", points)
    skeleton.set_radius(0.001)
    point_cloud.set_radius(0.005)
    point_cloud.set_color((1,0,0))
    ps.set_autoscale_structures(True)
    ps.show()
示例#7
0
def show_mesh_in_ply_file(obj_file):
    ps.init()
    vertex_pos = []
    face_indices = []
    flag = False
    with open(obj_file) as f_in:
        for line in f_in:
            temp = line.split(' ')
            if line == 'end_header\n':
                print('loading data')
                flag = True
                continue
            if flag == True:
                if temp[0] == '3':
                    face_indices.append(np.array([int(temp[1]), int(temp[2]), int(temp[3])]))
                else:
                    vertex_pos.append(np.array([float(temp[0]), float(temp[1]), float(temp[2])]))
    points = np.array(vertex_pos)
    faces = np.array(face_indices)
    ps_mesh = ps.register_surface_mesh("result mesh", points, faces)
    ps.set_autoscale_structures(True)
    ps.show()
示例#8
0
import sys

sys.path.append("src")

from geometry.smooth import curves
from geometry.discrete.shape import PolygonSpaceCurve
import numpy as np
import polyscope as ps

ps.init()

curve = curves.Line3D([1, 1, 1], [2, 4, 5])
path = PolygonSpaceCurve.from_space_curve(space_curve=curve, step=100)
ps_net = ps.register_curve_network("helix", path.vertices, "line")

ps.show()
示例#9
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = "Christian Heider Nielsen"
__doc__ = r"""

           Created on 16/04/2020
           """

import numpy
import polyscope

# Initialize polyscope
polyscope.init()


def generate_verts(n_pts=10):
    numpy.random.seed(777)
    return numpy.random.rand(n_pts, 3)


def generate_faces(n_pts=10):
    numpy.random.seed(777)
    return numpy.random.randint(0, n_pts, size=(2 * n_pts, 3))


verts, faces = generate_verts(), generate_faces()

### Register a point cloud
# `my_points` is a Nx3 numpy array
# ps.register_point_cloud("my points", my_points)
def main():

    parser = argparse.ArgumentParser()

    parser.add_argument('model_weights_path',
                        type=str,
                        help='path to the model checkpoint')
    parser.add_argument('input_path', type=str, help='path to the input')

    parser.add_argument('--disable_cuda',
                        action='store_true',
                        help='disable cuda')

    parser.add_argument('--sample_cloud',
                        type=int,
                        help='run on sampled points')

    parser.add_argument('--n_rounds',
                        type=int,
                        default=5,
                        help='number of rounds')
    parser.add_argument('--prob_thresh',
                        type=float,
                        default=.9,
                        help='threshold for final surface')

    parser.add_argument(
        '--output',
        type=str,
        help='path to save the resulting high prob mesh to. also disables viz')
    parser.add_argument('--output_trim_unused',
                        action='store_true',
                        help='trim unused vertices when outputting')

    # Parse arguments
    args = parser.parse_args()
    set_args_defaults(args)

    viz = not args.output
    args.polyscope = False

    # Initialize polyscope
    if viz:
        polyscope.init()

    # === Load the input

    if args.input_path.endswith(".npz"):
        record = np.load(args.input_path)
        verts = torch.tensor(record['vert_pos'],
                             dtype=args.dtype,
                             device=args.device)
        surf_samples = torch.tensor(record['surf_pos'],
                                    dtype=args.dtype,
                                    device=args.device)

        samples = verts.clone()
        faces = torch.zeros((0, 3), dtype=torch.int64, device=args.device)

        polyscope.register_point_cloud("surf samples", toNP(surf_samples))

    if args.input_path.endswith(".xyz"):
        raw_pts = np.loadtxt(args.input_path)
        verts = torch.tensor(raw_pts, dtype=args.dtype, device=args.device)

        samples = verts.clone()
        faces = torch.zeros((0, 3), dtype=torch.int64, device=args.device)

        polyscope.register_point_cloud("surf samples", toNP(verts))

    else:
        print("reading mesh")
        verts, faces = utils.read_mesh(args.input_path)
        print("  {} verts   {} faces".format(verts.shape[0], faces.shape[0]))
        verts = torch.tensor(verts, dtype=args.dtype, device=args.device)
        faces = torch.tensor(faces, dtype=torch.long, device=args.device)

        # verts = verts[::10,:]

        if args.sample_cloud:
            samples = mesh_utils.sample_points_on_surface(
                verts, faces, args.sample_cloud)
        else:
            samples = verts.clone()

    # === Load the model

    print("loading model weights")
    model = PointTriNet_Mesher()
    model.load_state_dict(torch.load(args.model_weights_path))

    model.eval()

    with torch.no_grad():

        # Sample lots of faces from the vertices
        print("predicting")
        candidate_triangles, candidate_probs = model.predict_mesh(
            samples.unsqueeze(0), n_rounds=args.n_rounds)
        candidate_triangles = candidate_triangles.squeeze(0)
        candidate_probs = candidate_probs.squeeze(0)
        print("done predicting")

        # Visualize
        high_prob = args.prob_thresh
        high_faces = candidate_triangles[candidate_probs > high_prob]
        closed_faces = mesh_utils.fill_holes_greedy(high_faces)

        if viz:
            polyscope.register_point_cloud("input points", toNP(samples))

            spmesh = polyscope.register_surface_mesh("all faces",
                                                     toNP(samples),
                                                     toNP(candidate_triangles),
                                                     enabled=False)
            spmesh.add_scalar_quantity("probs",
                                       toNP(candidate_probs),
                                       defined_on='faces')

            spmesh = polyscope.register_surface_mesh(
                "high prob mesh " + str(high_prob), toNP(samples),
                toNP(high_faces))
            spmesh.add_scalar_quantity(
                "probs",
                toNP(candidate_probs[candidate_probs > high_prob]),
                defined_on='faces')

            spmesh = polyscope.register_surface_mesh("hole-closed mesh " +
                                                     str(high_prob),
                                                     toNP(samples),
                                                     toNP(closed_faces),
                                                     enabled=False)

            polyscope.show()

        # Save output
        if args.output:

            high_prob = args.prob_thresh
            out_verts = toNP(samples)
            out_faces = toNP(high_faces)
            out_faces_closed = toNP(closed_faces)

            if args.output_trim_unused:
                out_verts, out_faces, _, _ = igl.remove_unreferenced(
                    out_verts, out_faces)

            igl.write_triangle_mesh(args.output + "_mesh.ply", out_verts,
                                    out_faces)
            write_ply_points(args.output + "_samples.ply", toNP(samples))

            igl.write_triangle_mesh(args.output + "_pred_mesh.ply", out_verts,
                                    out_faces)
            igl.write_triangle_mesh(args.output + "_pred_mesh_closed.ply",
                                    out_verts, out_faces_closed)
            write_ply_points(args.output + "_samples.ply", toNP(samples))
示例#11
0
 def __init__(self):
     ps.init()
     self.pcls = {}
示例#12
0
def show_points(points):
    ps.init()
    ps.register_point_cloud("points", points)
    ps_points = ps.get_point_cloud("points")
    ps_points.set_radius(0.0015)
    ps.show()
示例#13
0
def init():
    ps.init()