Ejemplo n.º 1
0
    def plotBsplineSurface(self,
                           pts,
                           corsequences,
                           lsagsequences=[],
                           rsagsequences=[],
                           degree=3,
                           visualization_type=-1,
                           side=2):
        # side = 0 (Left) | side = 1 (Right)

        if side == 0:
            lsurface = self.createBsplineSurface(pts=pts,
                                                 corsequences=corsequences,
                                                 sagsequences=lsagsequences)

            # Set visualization component
            if visualization_type == 0:
                lsurface.delta = 0.01
                vis_comp = VisMPL.VisSurfScatter()
            elif visualization_type == 1:
                vis_comp = VisMPL.VisSurface()
            elif visualization_type == 2:
                vis_comp = VisMPL.VisSurfWireframe()
            else:
                vis_comp = VisMPL.VisSurfTriangle()
            lsurface.vis = vis_comp

            # Render the surface
            lsurface.render()

        else:
            rsurface = self.createBsplineSurface(pts=pts,
                                                 corsequences=corsequences,
                                                 sagsequences=rsagsequences)

            # Set visualization component
            if visualization_type == 0:
                rsurface.delta = 0.01
                vis_comp = VisMPL.VisSurfScatter()
            elif visualization_type == 1:
                vis_comp = VisMPL.VisSurface()
            elif visualization_type == 2:
                vis_comp = VisMPL.VisSurfWireframe()
            else:
                vis_comp = VisMPL.VisSurfTriangle()
            rsurface.vis = vis_comp

            # Render the surface
            rsurface.render()
Ejemplo n.º 2
0
    def plotNURBSSurfaces(self,
                          left_pts,
                          right_pts,
                          corsequences,
                          lsagsequences,
                          rsagsequences,
                          degree=3,
                          visualization_type=-1):
        left_surface = self.createNURBSSurface(pts=left_pts,
                                               corsequences=corsequences,
                                               sagsequences=lsagsequences)
        right_surface = self.createNURBSSurface(pts=right_pts,
                                                corsequences=corsequences,
                                                sagsequences=rsagsequences)

        # Create a MultiSurface
        surfaces = Multi.MultiSurface()
        surfaces.add(left_surface)
        surfaces.add(right_surface)

        # Set visualization component
        if visualization_type == 0:
            surfaces.delta = 0.01
            vis_comp = VisMPL.VisSurfScatter()
        elif visualization_type == 1:
            vis_comp = VisMPL.VisSurface()
        elif visualization_type == 2:
            vis_comp = VisMPL.VisSurfWireframe()
        else:
            vis_comp = VisMPL.VisSurfTriangle()
        surfaces.vis = vis_comp

        # Render the surface
        surfaces.render()
Ejemplo n.º 3
0
    def surface_visualizer(self, surface):

        #%matplotlib

        # Create a visualization configuration instance with no legend, no axes and set the resolution to 120 dpi
        vis_config = VisMPL.VisConfig(ctrlpts=False, axes_equal=False)
        # Create a visualization method instance using the configuration above
        vis_obj = VisMPL.VisSurface(vis_config)
        # Set the visualization method of the curve object
        surface.vis = vis_obj
        surface.render(colormap=cm.cool, plot=False)
Ejemplo n.º 4
0
def test_deriv_surf_fig(bspline_surface):
    fname = "test-derivative_surface.png"

    data = operations.derivative_surface(bspline_surface)
    multi_shape = multi.SurfaceContainer(data)
    multi_shape.vis = VisMPL.VisSurface()
    multi_shape.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)
def test_surf_fig_nowindow(bspline_surface):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)

    fname = conf.figure_image_filename

    bspline_surface.vis = vis
    bspline_surface.render(plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(conf.figure_image_filename):
        os.remove(conf.figure_image_filename)
def test_surf_fig_save(bspline_surface):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)

    fname = "test-surface.png"

    bspline_surface.vis = vis
    bspline_surface.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)
Ejemplo n.º 7
0
def test_surf_multi_fig_save(bspline_surface):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)

    fname = "test-multi_surface.png"

    multi = operations.decompose_surface(bspline_surface)
    multi.vis = vis
    multi.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)
def test_surf_ctrlpts_offset(bspline_surface):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)

    # Set control points grid offset
    vis.ctrlpts_offset = 3.5

    fname = "test-surface.png"

    bspline_surface.vis = vis
    bspline_surface.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)
Ejemplo n.º 9
0
def build_vis(obj, **kwargs):
    """ Prepares visualization module for the input spline geometry.

    :param obj: input spline geometry object
    :return: spline geometry object updated with a visualization module
    """
    vis_config = VisMPL.VisConfig(**kwargs)
    if isinstance(obj, (NURBS.Curve, multi.CurveContainer)):
        if obj.dimension == 2:
            obj.vis = VisMPL.VisCurve2D(vis_config)
        elif obj.dimension == 3:
            obj.vis = VisMPL.VisCurve3D(vis_config)
        else:
            raise RuntimeError("Can only plot 2- or 3-dimensional curves")

    if isinstance(obj, (NURBS.Surface, multi.SurfaceContainer)):
        obj.vis = VisMPL.VisSurface(vis_config)

    if isinstance(obj, (NURBS.Volume, multi.VolumeContainer)):
        obj.vis = VisMPL.VisVolume(vis_config)

    return obj
Ejemplo n.º 10
0
# Set degrees
surf.degree_u = 3
surf.degree_v = 3

# Get the control points from the generated grid
surf.ctrlpts2d = surfgrid.grid

# Set knot vectors
surf.knotvector_u = utilities.generate_knot_vector(surf.degree_u, surf.ctrlpts_size_u)
surf.knotvector_v = utilities.generate_knot_vector(surf.degree_v, surf.ctrlpts_size_v)

# Set sample size of the surface
surf.sample_size = 50

# Generate the visualization component and its configuration
vis_config = vis.VisConfig(ctrlpts=True, legend=False)
vis_comp = vis.VisSurface(vis_config)

# Set visualization component of the surface
surf.vis = vis_comp

# Plot the surface
surf.render()

# Export the surface as a .stl file
exchange.export_stl(surf, "bump_smoother_1pt-padding.stl")

# Good to have something here to put a breakpoint
pass
Ejemplo n.º 11
0
os.chdir(os.path.dirname(os.path.realpath(__file__)))

# Create a NURBS surface instance
surf = NURBS.Surface()

# Set degrees
surf.degree_u = 1
surf.degree_v = 2

# Set control points
surf.set_ctrlpts(
    *exchange.import_txt("ex_cylinder_quarter.cptw", two_dimensional=True))

# Set knot vectors
surf.knotvector_u = [0, 0, 1, 1]
surf.knotvector_v = [0, 0, 0, 1, 1, 1]

# Set evaluation delta
surf.delta = 0.05

# Evaluate surface
surf.evaluate()

# Plot the control point grid and the evaluated surface
vis_comp = vis.VisSurface()
surf.vis = vis_comp
surf.render()

# Good to have something here to put a breakpoint
pass
Ejemplo n.º 12
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Examples for the NURBS-Python Package
    Released under MIT License
    Developed by Onur Rauf Bingol (c) 2018
"""
from geomdl.shapes import surface

# Try to load the visualization module
try:
    render = True
    from geomdl.visualization import VisMPL
except ImportError:
    render = False

cylinder = surface.cylinder(radius=5.0, height=22.5)
cylinder.delta = 0.05

# Render the surface
if render:
    vis_config = VisMPL.VisConfig(ctrlpts=False)
    vis_comp = VisMPL.VisSurface(config=vis_config)
    cylinder.vis = vis_comp
    cylinder.render()

# Good to have something here to put a breakpoint
pass
    surf03.ctrlpts2d = sg03.grid

    # Set knot vectors
    surf03.knotvector_u = utilities.generate_knot_vector(
        surf03.degree_u, surf03.ctrlpts_size_u)
    surf03.knotvector_v = utilities.generate_knot_vector(
        surf03.degree_v, surf03.ctrlpts_size_v)

    # Construct the parametric volume
    pvolume = construct.construct_volume(surf01, surf02, surf03, degree=1)
    pvolume.vis = vis.VisVoxel(vis.VisConfig(ctrlpts=False))
    pvolume.delta_u = pvolume.delta_v = 0.025
    pvolume.delta_w = 0.05
    pvolume.render(evalcolor="firebrick", use_mp=True, num_procs=16)

    # Extract surfaces from the parametric volume
    surfvol = construct.extract_surfaces(pvolume)

    # Construct the isosurface
    msurf = multi.SurfaceContainer(surfvol['uv'][0], surfvol['uv'][-1],
                                   surfvol['uw'][0], surfvol['uw'][-1],
                                   surfvol['vw'][0], surfvol['vw'][-1])
    msurf.vis = vis.VisSurface(vis.VisConfig(ctrlpts=False))
    msurf.delta = 0.05
    msurf.render(evalcolor=[
        "skyblue", "cadetblue", "crimson", "crimson", "crimson", "crimson"
    ])

# Good to have something here to put a breakpoint
pass
Ejemplo n.º 14
0
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)


surf_ed, surf_es, drdt_ed, drdz_ed, drdt_es, drdz_es = sinusoidal_cylinder()

surf_ed.delta = 0.025
# vis_config = vis.VisConfig(legend=True, axes=False, figure_dpi=120,ctrlpts = False)
surf_ed.vis = vis.VisSurface()
evalpts_ed = np.array(surf_ed.evalpts)

surf_es.delta = 0.025
surf_es.vis = vis.VisSurface()
evalpts_es = np.array(surf_es.evalpts)

# compute analytical metric tensor for ed phase
a_E_ed = []
a_F_ed = []
a_G_ed = []

for i in range(0, len(drdt_ed)):
    a_E_ed.append(np.dot(drdz_ed[i], drdz_ed[i]))
    a_F_ed.append(np.dot(drdz_ed[i], drdt_ed[i]))
    a_G_ed.append(np.dot(drdt_ed[i], drdt_ed[i]))
rect_size = np.array([20, 6, 6])
center = np.array([135, 300, 330])
radius = np.array([35, 35, 35])

margin = rect_size[0]
center += margin

img = tb.add_margin(inside, margin)
img = tb.window_function(img, 0, 300)
# tb.show_ct_image(img)

# surf = tb.make_ellipsoid_surf(center,radius)
tb.show_ct_image(tb.draw_contour(img, surf))

surf = tb.cul_contour(img,
                      surf,
                      rect_size,
                      div=20,
                      N_limit=30,
                      c=0.95,
                      ctrlpts_size=8,
                      dif_limit=0.001,
                      w=0.95)

surf.vis = VisMPL.VisSurface()
surf.render(colormap=cm.cool)

color_img = tb.draw_contour(img, surf)

tb.show_ct_image(color_img)
# Set control points
surf.set_ctrlpts(*exchange.import_txt("../ex_surface01.cpt", two_dimensional=True))

# Set knot vectors
surf.knotvector_u = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0]
surf.knotvector_v = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0]

# Set sample size
surf.sample_size = 30

# Set surface tessellation component
surf.tessellator = tessellate.TrimTessellate()

# Set visualization component
visconf = vis.VisConfig(ctrlpts=False, legend=False, trims=False)
surf.vis = vis.VisSurface(config=visconf)

# Generate circular trim curves with different sense
tcrv1 = analytic.Circle(origin=(0.25, 0.25), radius=0.20)
tcrv1.opt = ['sense', 1]
tcrv2 = analytic.Circle(origin=(0.75, 0.75), radius=0.20)
tcrv2.opt = ['sense', 1]
trim_curves = [tcrv1, tcrv2]

# Set trim curves (as a list)
surf.trims = trim_curves

# Visualize surface
surf.render(colormap=cm.copper)

# # Save as Wavefront OBJ file
Ejemplo n.º 17
0
    [0, 4, 0],
    [0, 8, -3],
    [2, 0, 6],
    [2, 4, 0],
    [2, 8, 0],
    [4, 0, 0],
    [4, 4, 0],
    [4, 8, 3],
    [6, 0, 0],
    [6, 4, -3],
    [6, 8, 0],
]
surf.set_ctrlpts(control_points, 4, 3)
surf.knotvector_u = [0, 0, 0, 0, 1, 1, 1, 1]
surf.knotvector_v = [0, 0, 0, 1, 1, 1]

# surf.delta = 0.05
surf.delta = 0.20  # 0.20 for testing, was originally 0.05 for smoothness

# 0.20, with 1.0 / 0.20 = 5.0,
# gives a matrix of [5x5] evalution points found by > surf.evalpts

# surf.vis = vis.VisSurface()
surf.vis = vis.VisSurface(vis.VisConfig(alpha=0.8))

surface_points = surf.evalpts
print(surface_points)
surf.render()

# surface 2, to come.
Ejemplo n.º 18
0
                                   degree_v)

surf = convert.bspline_to_nurbs(surf)
print("surf", type(surf))

# Extract curves from the approximated surface
surf_curves = construct.extract_curves(surf)
plot_extras = [
    dict(points=surf_curves['u'][0].evalpts, name="u", color="red", size=10),
    dict(points=surf_curves['v'][0].evalpts, name="v", color="black", size=10)
]
tube_pcl = np.array(surf.evalpts)
tube_cpts = np.array(surf.ctrlpts)

np.savetxt("cpts_tube.dat", tube_cpts, delimiter=' ')
from matplotlib import cm

surf.delta = 0.018
surf.vis = vis.VisSurface(ctrlpts=False)
surf.render(extras=plot_extras)
exchange.export_obj(surf, "fitted_helix.obj")
# visualize data samples, original RV data, and fitted surface

np.savetxt("RV_tube.dat", tube_pcl, delimiter=' ')

fig = plt.figure()
ax = plt.axes(projection="3d")
ax.scatter(tube_pcl[:, 0], tube_pcl[:, 1], tube_pcl[:, 2])
ax.scatter(points[:, 0], points[:, 1], points[:, 2], color="red")
plt.show()
Ejemplo n.º 19
0
def main():

    path = "d:/Workspace/RV-Mapping/RVshape/"
    rm_file = "rm_RVendo_0"
    std_file = "standardSample_15x25_RVendo_0"
    remapped_RV_file = path + rm_file
    standard_RV_file = path + std_file
    trimmed_rv_file = np.loadtxt("d:/Workspace/RV-Mapping/RVshape/transformed_RVendo_0.txt")
    # trimmed_rv_file = np.loadtxt("d:/Workspace/RV-Mapping.py/processed_RVendo_0.txt")

    std_rv_data = np.loadtxt(standard_RV_file + ".csv", delimiter=",")
    # std_rv_data = preProcess(std_rv_data)
    rm_rv_data = np.loadtxt(remapped_RV_file + ".txt", delimiter="\t")
    rm_rv_data = rm_rv_data[rm_rv_data[:,2] > 1]
    rm_rv_data = rm_rv_data[rm_rv_data[:,2] < max(rm_rv_data[:,2]) - 11]
    # rm_rv_data = preProcess(rm_rv_data)
    points = std_rv_data
    # np.savetxt("trimmed_" + rm_file + ".txt",rm_rv_data)
    
    N = 25
    M = 15
    # surf,sampled_data = fit_Remapped_RV(N,M, rm_rv_data,flag = False)
    surf = fit_Standard_RV(N,M, std_rv_data)
    fig = plt.figure()
    ax = plt.axes(projection="3d")
    # ax.scatter(trimmed_rv_file[:, 0],trimmed_rv_file[:, 1],trimmed_rv_file[:, 2])
    ax.scatter(std_rv_data[:, 0],std_rv_data[:, 1],std_rv_data[:, 2], s= 50,color = 'r')
    # ax.scatter(points[:, 0],points[:, 1],points[:, 2])
    # ax.scatter(sampled_data[:, 0],sampled_data[:, 1],sampled_data[:, 2] , color = 'r')
    # ax.scatter3D(0*np.ones((len(points))),0*np.ones((len(points))),points[:, 2],color = 'r')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.axis('off')
    plt.show()

    # fig = plt.figure()
    # ax = plt.axes(projection="3d")
    # ax.scatter(std_rv_data[:, 0],std_rv_data[:, 1],std_rv_data[:, 2], color = 'r')
    # ax.scatter(trimmed_rv_file[:, 0],trimmed_rv_file[:, 1],trimmed_rv_file[:, 2])
    # plt.axis('off')
    # plt.show()
    

    # np.savetxt("sampled_" + str(M) + 'x' + str(N) + '_' + rm_file + ".txt",sampled_data)
    

    # Extract curves from the approximated surface
    surf_curves = construct.extract_curves(surf)
    plot_extras = [
        dict(points=surf_curves["u"][0].evalpts, name="u", color="red", size=5),
        dict(points=surf_curves["v"][0].evalpts, name="v", color="black", size=5),
    ]
    surf.delta = 0.02
    surf.vis = vis.VisSurface()
    surf.render(extras=plot_extras)
    # exchange.export_obj(surf, rm_file + "_fit.obj")
    exchange.export_obj(surf, std_file + "_fit.obj")
    # # visualize data samples, original RV data, and fitted surface
    eval_surf = np.array(surf.evalpts)
    np.savetxt(std_file + "_NURBS_surf_pts.csv",eval_surf,delimiter = ',')
    # np.savetxt(rm_file + "_NURBS_surf_pts.csv",eval_surf,delimiter = ',')
    # # eval_surf = preProcess(eval_surf)

    fig = plt.figure()
    ax = plt.axes(projection="3d")
    ax.scatter(eval_surf[:,0],eval_surf[:,1],eval_surf[:,2], color = 'r')
    # ax.scatter3D(points[:, 0],points[:, 1],points[:, 2])
    ax.scatter3D(trimmed_rv_file[:, 0],trimmed_rv_file[:, 1],trimmed_rv_file[:, 2])
    # ax.scatter3D(xyz[:, 0],xyz[:, 1],xyz[:, 2])
    # ax.scatter(X[:,0],X[:,1],X[:,2])

    # # ax.scatter(X[:,0],X[:,1],X[:,2])
    cpts = np.array(surf.ctrlpts)
    print(len(cpts))
    # np.savetxt('cpts_'+rm_file+".csv",cpts, delimiter = ',')
    np.savetxt('cpts_'+ std_file + ".csv",cpts, delimiter = ',')
    # fig = plt.figure()
    # ax = plt.axes(projection = "3d")
    # ax.scatter(X[:,0],X[:,1],X[:,2])
    # ax.scatter(cpts[:,0],cpts[:,1],cpts[:,2])
    plt.show()
Ejemplo n.º 20
0
def main():
    points = np.loadtxt("N2_RV_P0.txt")

    zmin_loc_temp = np.where(points[:, 1] == 0)[0]
    zmin_loc = zmin_loc_temp

    # points = remove_3dpoint(points,zmin_loc)
    N = 5
    slice(N, points)

    slice0 = slice.slices[0]
    x0 = slice0[:, 0]
    y0 = slice0[:, 1]
    z0 = slice0[:, 2]
    slice1 = slice.slices[1]
    x1 = slice1[:, 0]
    y1 = slice1[:, 1]
    z1 = slice1[:, 2]
    slice2 = slice.slices[2]
    x2 = slice2[:, 0]
    y2 = slice2[:, 1]
    z2 = slice2[:, 2]
    slice3 = slice.slices[3]
    x3 = slice3[:, 0]
    y3 = slice3[:, 1]
    z3 = slice3[:, 2]
    slice4 = slice.slices[4]
    x4 = slice4[:, 0]
    y4 = slice4[:, 1]
    z4 = slice4[:, 2]
    print(np.shape(points))
    ranges = slice.bins

    diameter = x0.max() - x0.min()
    radius = diameter
    height = z0.max()

    diameter1 = x1.max() - x1.min()
    radius1 = diameter1
    height1 = z1.max()

    diameter2 = x2.max() - x2.min()
    radius2 = diameter2
    height2 = z2.max()

    diameter3 = x3.max() - x3.min()
    radius3 = diameter3
    height3 = z3.max()

    diameter4 = x4.max() - x4.min()
    radius4 = diameter4 / 2
    height4 = x4.max()

    # Generate a cylindrical surface using the shapes component
    cylinder = surface.cylinder(radius, height)
    # vis_config = VisMPL.VisConfig(ctrlpts=True)
    # vis_comp = VisMPL.VisSurface(config=vis_config)
    # cylinder.vis = vis_comp
    # cylinder.render()
    cyl_points = cylinder.evalpts
    print("*****************")
    # print(len(cyl_points))
    print("*****************")

    cylinder1 = surface.cylinder(radius1, height1)
    cyl_points1 = cylinder1.evalpts
    # vis_config = VisMPL.VisConfig(ctrlpts=True)
    # vis_comp = VisMPL.VisSurface(config=vis_config)
    # cylinder1.vis = vis_comp
    # cylinder1.render()

    cylinder2 = surface.cylinder(radius2, height2)
    cyl_points2 = cylinder2.evalpts
    # vis_config = VisMPL.VisConfig(ctrlpts=True)
    # vis_comp = VisMPL.VisSurface(config=vis_config)
    # cylinder2.vis = vis_comp
    # cylinder2.render()

    cylinder3 = surface.cylinder(radius3, height3)
    cyl_points3 = cylinder3.evalpts
    # vis_config = VisMPL.VisConfig(ctrlpts=True)
    # vis_comp = VisMPL.VisSurface(config=vis_config)
    # cylinder2.vis = vis_comp
    # cylinder2.render()

    cylinder4 = surface.cylinder(radius4, height4)
    cyl_points4 = cylinder4.evalpts
    # vis_config = VisMPL.VisConfig(ctrlpts=True)
    # vis_comp = VisMPL.VisSurface(config=vis_config)
    # cylinder4.vis = vis_comp
    # cylinder4.render()

    #try using points from the surface not the control points
    cylinder_cpts = np.array(cylinder.ctrlpts)
    cylinder_cpts1 = np.array(cylinder1.ctrlpts)
    cylinder_cpts2 = np.array(cylinder2.ctrlpts)
    cylinder_cpts3 = np.array(cylinder3.ctrlpts)
    cylinder_cpts4 = np.array(cylinder4.ctrlpts)

    a = np.array(cdist(np.array(cyl_points), slice0)).min(axis=0)
    b = np.array(cdist(np.array(cyl_points1), slice1)).min(axis=0)
    c = np.array(cdist(np.array(cyl_points2), slice2)).min(axis=0)
    d = np.array(cdist(np.array(cyl_points3), slice3)).min(axis=0)
    e = np.array(cdist(np.array(cyl_points4), slice4)).min(axis=0)

    test = np.zeros((len(cylinder_cpts), 3))
    test1 = np.zeros((len(cylinder_cpts1), 3))
    test2 = np.zeros((len(cylinder_cpts2), 3))
    test3 = np.zeros((len(cylinder_cpts3), 3))
    test4 = np.zeros((len(cylinder_cpts4), 3))

    for i in range(0, len(cylinder_cpts)):
        test[i] = (cylinder_cpts[i] / np.linalg.norm(cylinder_cpts[i])) * a[i]
        test1[i] = (cylinder_cpts1[i] /
                    np.linalg.norm(cylinder_cpts1[i])) * b[i]
        test2[i] = (cylinder_cpts2[i] /
                    np.linalg.norm(cylinder_cpts2[i])) * c[i]
        test3[i] = (cylinder_cpts3[i] /
                    np.linalg.norm(cylinder_cpts3[i])) * d[i]
        test4[i] = (cylinder_cpts4[i] /
                    np.linalg.norm(cylinder_cpts4[i])) * e[i]

    test_zeros_loc = np.where(test[:, 2] == 0)[0]
    test1_zeros_loc = np.where(test1[:, 2] == 0)[0]
    test2_zeros_loc = np.where(test2[:, 2] == 0)[0]
    test3_zeros_loc = np.where(test3[:, 2] == 0)[0]
    test4_zeros_loc = np.where(test4[:, 2] == 0)[0]

    test = remove_3dpoint(test, test_zeros_loc)
    test1 = remove_3dpoint(test1, test1_zeros_loc)
    test2 = remove_3dpoint(test2, test2_zeros_loc)
    test3 = remove_3dpoint(test3, test3_zeros_loc)
    test4 = remove_3dpoint(test4, test4_zeros_loc)

    test = np.array(
        [test[:, 0], test[:, 1],
         np.ones(len(test[:, 2])) * ranges[0]]).T
    test1 = np.array(
        [test1[:, 0], test1[:, 1],
         np.ones(len(test1[:, 2])) * ranges[1]]).T
    test2 = np.array(
        [test2[:, 0], test2[:, 1],
         np.ones(len(test2[:, 2])) * ranges[2]]).T
    test3 = np.array(
        [test3[:, 0], test3[:, 1],
         np.ones(len(test3[:, 2])) * ranges[3]]).T
    test4 = np.array(
        [test4[:, 0], test4[:, 1],
         np.ones(len(test4[:, 2])) * ranges[4]]).T

    # for i in range(0,len(test1)):
    # test1[i] = test1[i] + [0,0,height]
    # test2[i] = test2[i]+[0,0,height1]
    # test3[i] = test3[i]+[0,0,height2]

    test = remove_3dpoint(test, len(test) - 1)
    test1 = remove_3dpoint(test1, len(test1) - 1)
    test2 = remove_3dpoint(test2, len(test2) - 1)
    test3 = remove_3dpoint(test3, len(test3) - 1)
    test4 = remove_3dpoint(test4, len(test4) - 1)

    # test = np.insert(test,[0,len(test)],[[0,0,-5],[0,0,ranges[0]]],axis=0)
    # test1 = np.insert(test1,[0,len(test1)],[0,0,ranges[1]],axis=0)
    # test2 = np.insert(test2,[0,len(test2)],[0,0,ranges[2]],axis=0)
    test = np.insert(
        test,
        [len(test) - 2, len(test) - 1, len(test)], [test[0], test[1], test[2]],
        axis=0)
    test1 = np.insert(
        test1, [len(test1) - 2, len(test1) - 1,
                len(test1)], [test1[0], test1[1], test1[2]],
        axis=0)
    test2 = np.insert(
        test2, [len(test2) - 2, len(test2) - 1,
                len(test2)], [test2[0], test2[1], test2[2]],
        axis=0)
    test3 = np.insert(
        test3, [len(test3) - 2, len(test3) - 1,
                len(test3)], [test3[0], test3[1], test3[2]],
        axis=0)
    test = np.insert(
        test4, [len(test4) - 2, len(test4) - 1,
                len(test4)], [test4[0], test4[1], test4[2]],
        axis=0)

    # print(test)
    # print(test1)
    # print(test2)
    # print(test3)

    X = np.row_stack((test, test1, test2, test3, test4))
    print(X)
    # np.random.shuffle(X)

    np.savetxt("cpts_test.csv", X, delimiter=",")
    # np.savetxt("cpts_test1.csv", test1, delimiter=",")
    fig = plt.figure()
    ax = plt.axes(projection="3d")
    ax.scatter3D(test[:, 0],
                 test[:, 1],
                 np.ones(len(test[:, 2])) * ranges[0],
                 color='red')
    ax.scatter3D(test1[:, 0], test1[:, 1], test1[:, 2], color='blue')
    ax.scatter3D(test2[:, 0], test2[:, 1], test2[:, 2], color='green')
    ax.scatter3D(test3[:, 0], test3[:, 1], test3[:, 2], color='yellow')
    ax.scatter3D(test4[:, 0], test4[:, 1], test4[:, 2], color='purple')
    # ax.scatter3D(cylinder_cpts[:,0],cylinder_cpts[:,1],cylinder_cpts[:,2])
    # ax.scatter3D(cylinder_cpts1[:,0],cylinder_cpts1[:,1],cylinder_cpts1[:,2])

    # try fitting a NURBS Surface
    surf = NURBS.Surface()
    surf.delta = 0.03
    p_ctrlpts = exchange.import_csv("cpts_test.csv")
    print(len(p_ctrlpts))
    p_weights = np.ones((len(p_ctrlpts)))
    p_size_u = 9
    p_size_v = 5
    p_degree_u = 3
    p_degree_v = 3
    t_ctrlptsw = compat.combine_ctrlpts_weights(p_ctrlpts, p_weights)
    n_ctrlptsw = compat.flip_ctrlpts_u(t_ctrlptsw, p_size_u, p_size_v)
    n_knotvector_u = utils.generate_knot_vector(p_degree_u, p_size_u)
    n_knotvector_v = utils.generate_knot_vector(p_degree_v, p_size_v)

    surf.degree_u = p_degree_u
    surf.degree_v = p_degree_v
    surf.set_ctrlpts(n_ctrlptsw, p_size_u, p_size_v)
    surf.knotvector_u = n_knotvector_u
    surf.knotvector_v = n_knotvector_v
    vis_config = vis.VisConfig(ctrlpts=True, axes=True, legend=True)
    surf.vis = vis.VisSurface(vis_config)
    surf.evaluate()
    surf.render()
Ejemplo n.º 21
0
def helix():

    # create starting parameters for helix
    M = 20
    t = np.linspace(0, 2 * np.pi / 3, M)
    a = 30
    b = 30

    s = []
    C = a**2 + b**2
    for i in range(0, len(t)):
        s.append(np.sqrt(C) * t[i])

    r = []
    T = []
    N = []
    B = []

    for i in range(0, len(s)):
        # generate a helical axis first
        r.append([
            a * np.cos(s[i] / np.sqrt(C)), a * np.sin(s[i] / np.sqrt(C)),
            b * s[i] / np.sqrt(C)
        ])

        # create the tangential, normal, and binormal vectors
        T.append([
            -a / np.sqrt(C) * np.sin(s[i] / np.sqrt(C)),
            a / np.sqrt(C) * np.cos(s[i] / np.sqrt(C)), b / np.sqrt(C)
        ])
        N.append([-np.cos(s[i] / np.sqrt(C)), -np.sin(s[i] / np.sqrt(C)), 0])

    B.append(np.cross(T, N))

    # store them as numpy arrays for convenience
    r = np.array(r)
    Ts = np.array(T)
    Ns = np.array(N)
    Bs = np.array(B[0])

    # scatter the T, N, and B vectors
    fig = plt.figure()
    ax = plt.axes(projection="3d")

    # these scatter points serves as a check to make sure that the T, N , B vectors work

    # ax.plot(r[:,0],r[:,1],r[:,2],color = 'r')
    # ax.scatter(r[5,0]+Ts[5,0],r[5,1]+Ts[5,1],r[5,2]+Ts[5,2],color = 'b')
    # ax.scatter(r[5,0],r[5,1],r[5,2],color = 'k')
    # ax.scatter(r[5,0]-Ts[5,0],r[5,1]-Ts[5,1],r[5,2]-Ts[5,2],color = 'g')

    # ax.scatter(Bs[:,0],Bs[:,1],Bs[:,2],color = 'g')
    # ax.scatter(Ns[:,0],Ns[:,1],Ns[:,2],color = 'b')

    helix = []
    phi = np.linspace(0, 2 * np.pi, M)
    d = 10
    for i in range(0, len(s)):
        for j in range(0, len(phi)):
            helix.append([
                d * Bs[i, 0] * np.cos(phi[j]) + d * Ns[i, 0] * np.sin(phi[j]) +
                r[i, 0], d * Bs[i, 1] * np.cos(phi[j]) +
                d * Ns[i, 1] * np.sin(phi[j]) + r[i, 1],
                d * Bs[i, 2] * np.cos(phi[j]) + d * Ns[i, 2] * np.sin(phi[j]) +
                r[i, 2]
            ])

    helix = np.array(helix)
    np.savetxt("helical_cylinder.csv", helix, delimiter=',')

    ax.scatter(helix[:, 0], helix[:, 1], helix[:, 2])
    ax.set_title("Helical Tube Point Cloud")
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    plt.show()
    p_ctrlpts = helix
    size_u = M
    size_v = M
    degree_u = 3
    degree_v = 3

    # Do global surface approximation
    surf = fitting.approximate_surface(p_ctrlpts, size_u, size_v, degree_u,
                                       degree_v)

    surf = convert.bspline_to_nurbs(surf)

    # Extract curves from the approximated surface
    surf_curves = construct.extract_curves(surf)
    plot_extras = [
        dict(points=surf_curves['u'][0].evalpts,
             name="u",
             color="red",
             size=10),
        dict(points=surf_curves['v'][0].evalpts,
             name="v",
             color="black",
             size=10)
    ]
    tube_pcl = np.array(surf.evalpts)
    tube_cpts = np.array(surf.ctrlpts)

    # np.savetxt("cpts_bezier.dat",r,delimiter = ',')
    # from matplotlib import cm
    surf.delta = 0.02
    surf.vis = vis.VisSurface()
    surf.render(extras=plot_extras)
    exchange.export_obj(surf, "helix.stl")
    np.savetxt("RV_tube.dat", tube_pcl, delimiter=' ')
    # np.savetxt("tube_cpts.dat",tube_cpts,delimiter = ' ')
    np.savetxt("tube_cpts.csv", tube_cpts, delimiter=',')

    # crv = BSpline.Curve()
    # crv.degree = 3
    # crv.ctrlpts = exchange.import_txt("cpts_tube.dat")
    # crv.knotvector = knotvector.generate(crv.degree, crv.ctrlpts_size)

    # # Set the visualization component of the curve
    # crv.vis = vis.VisCurve3D()

    # # Plot the curve
    # crv.render()
    return surf
Ejemplo n.º 22
0
    def plotBsplineSurfaces(self,
                            left_pts,
                            right_pts,
                            corsequences,
                            lsagsequences,
                            rsagsequences,
                            degree=3,
                            visualization_type=-1):
        """ Create B-spline surface

        Parameters
        ----------
        left_pts: list
            List of tuples with 3D points that represents the left diaphragmatic surface

        right_pts: list
            List of tuples with 3D points that represents the right diaphragmatic surface

        corsequences: list
            List of int with the coronal sequences available

        lsagsequences: list
            List of int with the sagittal sequences available from the left lung

        rsagsequences: list
            List of int with the sagittal sequences available from the right lung

        degree: int
            B-spline surface's Degree (Default = 2)

        visualization_type: int
            -1: (Default) Wireframe plot for the control points and triangulated plot for the surface points
            0: Wireframe plot for the control points and scatter plot for the surface points
            1: Triangular mesh plot for the surface and wireframe plot for the control points grid
            2: Scatter plot for the control points and wireframe for the surface points
        """
        left_surface = self.createBsplineSurface(pts=left_pts,
                                                 corsequences=corsequences,
                                                 sagsequences=lsagsequences)
        right_surface = self.createBsplineSurface(pts=right_pts,
                                                  corsequences=corsequences,
                                                  sagsequences=rsagsequences)

        # Create a MultiSurface
        surfaces = Multi.MultiSurface()
        surfaces.add(left_surface)
        surfaces.add(right_surface)

        # Set visualization component
        if visualization_type == 0:
            surfaces.delta = 0.01
            vis_comp = VisMPL.VisSurfScatter()
        elif visualization_type == 1:
            vis_comp = VisMPL.VisSurface()
        elif visualization_type == 2:
            vis_comp = VisMPL.VisSurfWireframe()
        else:
            vis_comp = VisMPL.VisSurfTriangle()
        surfaces.vis = vis_comp

        # Render the surface
        surfaces.render()
Ejemplo n.º 23
0
        name="u",
        color="red",
        size=10
    ),
    dict(
        points=surf_curves['v'][0].evalpts,
        name="v",
        color="black",
        size=10
    )
]
toroid_pcl = np.array(surf.evalpts)
np.savetxt("tapered_toroid_pcl.csv",toroid_pcl,delimiter = ',')
toroid_cpts = np.array(surf.ctrlpts)
np.savetxt("toroid_cpts.csv",toroid_cpts,delimiter = ',',fmt = "%1.3f")
print(len(toroid_cpts))
# np.savetxt("cpts_bezier.dat",r,delimiter = ',')
# from matplotlib import cm
surf.delta = 0.03

surf.vis = vis.VisSurface()
surf.render(extras=plot_extras)
exchange.export_obj(surf, "tapered_toroid.obj")
np.savetxt("tapered_toroid.dat",toroid_pcl,delimiter = ' ')
# np.savetxt("tube_cpts.dat",tube_cpts,delimiter = ' ')


plt.show()


Ejemplo n.º 24
0
 def vis_spline_surf(self, surf):
     surf.vis = VisMPL.VisSurface()
     surf.render()
Ejemplo n.º 25
0
# Fix file path
os.chdir(os.path.dirname(os.path.realpath(__file__)))

# Create a BSpline surface instance (Bezier surface)
surf = BSpline.Surface()

# Set up the Bezier surface
surf.degree_u = 3
surf.degree_v = 2
control_points = [[0, 0, 0], [0, 4, 0], [0, 8, -3], [2, 0, 6], [2, 4, 0],
                  [2, 8, 0], [4, 0, 0], [4, 4, 0], [4, 8, 3], [6, 0, 0],
                  [6, 4, -3], [6, 8, 0]]
surf.set_ctrlpts(control_points, 4, 3)
surf.knotvector_u = utilities.generate_knot_vector(surf.degree_u,
                                                   surf.ctrlpts_size_u)
surf.knotvector_v = utilities.generate_knot_vector(surf.degree_v,
                                                   surf.ctrlpts_size_v)

# Set sample size
surf.sample_size = 25

# Evaluate surface
surf.evaluate()

# Plot the control point grid and the evaluated surface
vis_comp = VisMPL.VisSurface()
surf.vis = vis_comp
surf.render()

pass
Ejemplo n.º 26
0
 def vis_multiple_spline_surf(self, surfs):
     mcrv = multi.SurfaceContainer([surf, surf1])
     mcrv.vis = VisMPL.VisSurface()
     mcrv.render()
Ejemplo n.º 27
0
surf1.set_ctrlpts(
    *exchange.import_txt("ex_surface01.cpt", two_dimensional=True))

# Set knot vectors
surf1.knotvector_u = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0]
surf1.knotvector_v = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0]

# Set evaluation delta
surf1.delta = 0.025

# Rotate surf1 and generate a copy in surf2
surf2 = operations.rotate(surf1, 45, axis=2)

# Visualize surfaces
msurf1 = multi.SurfaceContainer(surf1, surf2)
msurf1.vis = vis.VisSurface()
msurf1.render()

# Decompose surf1
surf1_decomposed = operations.decompose_surface(surf1)
msurf2 = multi.SurfaceContainer(surf1_decomposed)

# Rotate decomposed surface
msurf2_rotated = operations.rotate(msurf2, 90, axis=1)

# Visualize decomposed and decomposed-rotated surfaces
msurf3 = multi.SurfaceContainer(msurf2, msurf2_rotated)
msurf3.vis = vis.VisSurface()
msurf3.render()

# Good to have something here to put a breakpoint
Ejemplo n.º 28
0
    def _execute(self):

        print('Process of field surface evaluation started')
        start = time.time()
        if not os.path.exists(self.path + 'surface_evaluation/'):
            os.makedirs(self.path + 'surface_evaluation/')

        odP = outlier_detector_Parameters()
        tfP = terrain_filter_Parameters()
        tgP = terrain_grid_Parameters()
        sfP = surface_fit_Parameters()

        out_flag = self.outlier_detector(points=self.dws_point_cloud,
                                         metric=odP.METRIC,
                                         method=odP.METHOD,
                                         radius=odP.RADIUS,
                                         deviance=odP.DEVIANCE,
                                         K=odP.K)

        store_point_cloud(self.path + 'surface_evaluation/' + "clean_roi.las",
                          self.dws_point_cloud[out_flag, :], self.header)
        save_img(self.dws_point_cloud[out_flag, :], 'clean_roi_0_0',
                 self.path + 'surface_evaluation/', 0, 0)
        save_img(self.dws_point_cloud[out_flag, :], 'clean_roi_0_90',
                 self.path + 'surface_evaluation/', 0, 90)

        print('outliers removed .....')
        terrain_points = self.terrain_filter(
            points=self.dws_point_cloud[out_flag, :],
            method=tfP.METHOD,
            window_size=tfP.WINDOW_SIZE,
            window_stride=tfP.WINDOW_STRIDE,
            quantile=tfP.WINDOW_QUANTILE,
            k=tfP.K)
        print('terrain points founded .....')
        terrain_grid_points = self.terrain_grid(
            points=terrain_points,
            metric=tgP.METRIC,
            K=tgP.K,
            grid_resolution=tgP.GRID_RESOLUTION)
        print('terrain grid was formed .....')

        surface = self.surface_fit(terrain_grid=terrain_grid_points,
                                   grid_resolution=tgP.GRID_RESOLUTION,
                                   u_degree=sfP.U_DEGREE,
                                   v_degree=sfP.V_DEGREE,
                                   delta=sfP.DELTA)
        # Create a visualization configuration instance with no legend, no axes and set the resolution to 120 dpi
        vis_config = VisMPL.VisConfig(ctrlpts=False, axes_equal=False)
        # Create a visualization method instance using the configuration above
        vis_obj = VisMPL.VisSurface(vis_config)
        # Set the visualization method of the curve object
        surface.vis = vis_obj
        surface.render(filename=self.path + 'surface_evaluation/' +
                       "terrain.png",
                       colormap=cm.cool,
                       plot=False)
        print('surface was modeled .....')

        # Get the evaluated points
        surface_points = np.array(surface.evalpts)
        print('de-terrain points process')

        deTerreained_points = np.zeros_like(self.dws_point_cloud[out_flag, :])

        for i, point in enumerate(tqdm(self.dws_point_cloud[out_flag, :])):

            clean_point = point.copy()
            point_dist = np.array(
                ((surface_points[:, 0] - point[0])**2 +
                 (surface_points[:, 1] - point[1])**2)**(0.5))

            clean_point[2] = clean_point[2] - surface_points[
                np.argmin(point_dist), 2]
            deTerreained_points[i] = clean_point

        deTerreained_points[:, 2] = deTerreained_points[:, 2] + np.abs(
            deTerreained_points[:, 2].min())
        store_point_cloud(
            self.path + 'surface_evaluation/' + "de-terrained_roi.las",
            deTerreained_points, self.header)

        save_img(deTerreained_points, 'de-terrained_roi_0_0',
                 self.path + 'surface_evaluation/', 0, 0)
        save_img(deTerreained_points, 'de-terrained_roi_0_90',
                 self.path + 'surface_evaluation/', 0, 90)
        print('point cloud was de-terrained ......')
        end = time.time()

        print('Time:{}'.format(end - start))
Ejemplo n.º 29
0
import numpy as np
import matplotlib.pyplot as plt
from geomdl import fitting
from geomdl import convert
from geomdl import construct
from geomdl.visualization import VisMPL as vis
import sys
np.set_printoptions(threshold=sys.maxsize)
from tools import preProcess
from geomdl import exchange
from geomdl import knotvector
from geomdl import BSpline
from generateHelix import helix

ctrlpts = np.loadtxt("test1.txt")
np.savetxt("candidate_cpts.csv", ctrlpts, delimiter=',')
helix = helix()
c = np.array(helix.ctrlpts)
print(c)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.scatter(c[:, 0], c[:, 1], c[:, 2])

helix.ctrlpts = ctrlpts
helix.delta = 0.015
helix.vis = vis.VisSurface()
helix.render()
exchange.export_obj(helix, "trial0.obj")
Ejemplo n.º 30
0
            [-15.0, 15.0, 0.0, 1.0], [-25.0, 15.0, 0.0, 1.0]],
           [[25.0, 25.0, 0.0, 1.0], [15.0, 25.0, 0.0, 1.0],
            [5.0, 25.0, 5.0, 1.0], [-5.0, 25.0, 5.0, 1.0],
            [-15.0, 25.0, 0.0, 1.0], [-25.0, 25.0, 0.0, 1.0]]]

# Generate surface
surf = NURBS.Surface()
surf.degree_u = 3
surf.degree_v = 3
surf.ctrlpts2d = ctrlpts
surf.knotvector_u = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0]
surf.knotvector_v = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0]
surf.sample_size = 30

# Set visualization component
surf.vis = VisMPL.VisSurface(
    VisMPL.VisConfig(alpha=0.75, figure_size=[10.66, 8]))

# Visualize
surf.render(filename="surf01.png", plot=False)

# Create a deep copy of the surface
surf_refined = deepcopy(surf)

# Refine knot vectors
operations.refine_knotvector(surf_refined, [1, 1])

# Visualize after knot vector refinement
surf_refined.render(filename="surf02.png", plot=False)

# Create a deep copy of the surface
surf_refined = deepcopy(surf)