def display_curve(curve, ctrlpts=True):
    # Generate the visualisation configuration
    vis_config = VisMPL.VisConfig(legend=True, ctrlpts=ctrlpts)
    vis_comp = VisMPL.VisCurve2D(vis_config)
    # Draw the control point polygon and the evaluated curve
    curve.vis = vis_comp
    curve.render()
Пример #2
0
    def test_NURBS_BSPLINE_EQUAL(self):
        # Save results
        B_res = self.B_cur.evalpts
        N_res = self.N_cur.evalpts

        # Plot the control point polygon and the evaluated curve
        vis_comp = vis.VisCurve2D()
        self.N_cur.vis = vis_comp
        # self.N_cur.render()
        self.assertListAlmostEqual(B_res, N_res, 3)
Пример #3
0
    def test_gauss_newton2D(self):
        ''' Performs gauss newton search of optimum weights
        '''

        # Fit the NURBS weights and control points
        N_fit = F.gauss_newton2D(self.N_cur, self.points)

        # Plot (debug)
        fig = plt.figure(num=1)
        vis_fit = vis.VisCurve2D()
        N_fit.vis = vis_fit
        N_fit.render()
Пример #4
0
def draw_curve(curve):
    # Try to load the visualization module
    try:
        render_curve = True
        from geomdl.visualization import VisMPL
    except ImportError:
        render_curve = False

    # Draw the control point polygon and the evaluated curve
    if render_curve:
        vis_comp = VisMPL.VisCurve2D()
        curve.vis = vis_comp
        curve.render()
Пример #5
0
def test_deriv_curve_fig(bspline_curve2d):
    fname = "test-derivative_curve.png"

    data = operations.derivative_curve(bspline_curve2d)
    multi_shape = multi.CurveContainer(data)
    multi_shape.vis = VisMPL.VisCurve2D()
    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)
Пример #6
0
def plot_BC(BC_ctrlpts, BC_knot, p):
    """Plot a boundary curve

	:param BC_ctrlpts: boundary control points
	:param BC_knot: boundary knot vector
	:param p: boundary degree
	"""
    cu = NURBS.Curve()
    cu.degree = p
    cu.ctrlpts = BC_ctrlpts.tolist()
    cu.knotvector = BC_knot
    cu.delta = 0.01
    # Plot the control point polygon and the evaluated curve
    cu.vis = VisMPL.VisCurve2D()
    cu.render()
Пример #7
0
def run(N, weight):
    N = N
    circle = create_curve(N)
    print(circle)
    weight = math.cos(math.pi / N) + weight
    cv = Multi.MultiCurve()
    k = 0
    while k < len(circle) - 1:
        cv.add(
            create_bezie_curve(circle[k], circle[k + 1], circle[k + 2],
                               weight))
        k = k + 2
    vis_compl = VisMPL.VisCurve2D()
    cv.vis = vis_compl
    cv.render()
def test_curve3d_fig_nowindow(bspline_curve3d):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve2D(config=conf)

    fname = conf.figure_image_filename

    bspline_curve3d.vis = vis
    bspline_curve3d.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_curve2d_fig_save(bspline_curve2d):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve2D(config=conf)

    fname = "test-curve.png"

    bspline_curve2d.vis = vis
    bspline_curve2d.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_curve2d_multi_fig_save(bspline_curve2d):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve2D(config=conf)

    fname = "test-multi_curve.png"

    multi = operations.decompose_curve(bspline_curve2d)
    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_curve2d_multi_fig_nowindow(bspline_curve2d):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve2D(config=conf)

    fname = conf.figure_image_filename

    multi = operations.decompose_curve(bspline_curve2d)
    multi.vis = vis
    multi.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)
Пример #12
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
Пример #13
0
# Fix file path
os.chdir(os.path.dirname(os.path.realpath(__file__)))

# Create a BSpline (NUBS) curve instance
curve = BSpline.Curve()

# Set degree
curve.degree = 2

# Set control points for a periodic curve
curve.ctrlpts = [[1, 0], [-1, 0], [-1.5, 1.5], [1.5, -1.5], [1, 0], [-1, 0]]

# Knot vector
curve.knotvector = [0, 1, 2, 3, 4, 5, 6, 7, 8]

# Set evaluation delta
curve.sample_size = 100

# Evaluate curve
curve.evaluate()

# Draw the control point polygon and the evaluated curve
vis_config = VisMPL.VisConfig(ctrlpts=False, legend=False)
vis_comp = VisMPL.VisCurve2D(vis_config)
curve.vis = vis_comp
curve.render()

# Good to have something here to put a breakpoint
pass
Пример #14
0
# Try to load the visualization module
try:
    render = True
    from geomdl.visualization import VisMPL
except ImportError:
    render = False

# Generate a NURBS full circle from 7 control points
circle = curve2d.full_circle2(radius=5.0)
circle.delta = 0.01

# Render the circle and the control points polygon
if render:
    vis_config = VisMPL.VisConfig(ctrlpts=True, figure_size=[9, 8])
    vis_comp = VisMPL.VisCurve2D(config=vis_config)
    circle.vis = vis_comp
    circle.render()

# Decompose the circle into Bezier curve segments
bezier_segments = circle.decompose()

# Prepare Bezier segments for plotting
bezier_segments.delta = 0.01

# Render the Bezier curve segments and their control points polygons
if render:
    vis_config = VisMPL.VisConfig(ctrlpts=True, figure_size=[9, 8])
    vis_comp = VisMPL.VisCurve2D(config=vis_config)
    bezier_segments.vis = vis_comp
    bezier_segments.render()
Пример #15
0
curve.ctrlpts = [[1.0,1.0], [2.5,0.5], [5.0,1.0]]
curve.degree = 1

# Auto-generate knot vector
curve.knotvector = utilities.generate_knot_vector(curve.degree, len(curve.ctrlpts))

# Length computation
xi=[-0.57735, 0.57735]
wi=[1, 1]
g1= lambda t: curve.derivatives(0.25*t+0.25, 1)
dcurve1 = np.array([g1(xi[i])[1] for i in range(len(xi))])
length1 = 0.25*np.dot(wi, np.linalg.norm(dcurve1, axis=1))
print length1
l1 = np.linalg.norm(np.array(curve.ctrlpts[1]) - np.array(curve.ctrlpts[0]))
l2 = np.linalg.norm(np.array(curve.ctrlpts[2]) - np.array(curve.ctrlpts[1]))
print 'l1 = ', l1
print 'l2 = ', l2
print 'ana lengh=', l1+l2

sys.exit(0)
# Set evaluation delta
curve.delta = 0.01

# Evaluate curve
curve.evaluate()

# Draw the control point polygon and the evaluated curve
if render_curve:
    vis_comp = VisMPL.VisCurve2D()
    curve.vis = vis_comp
    curve.render()
Пример #16
0
    Examples for the NURBS-Python Package
    Released under MIT License
    Developed by Onur Rauf Bingol (c) 2018

    2-dimensional curve fitting by global interpolation
"""

from geomdl import fitting
from geomdl.visualization import VisMPL as vis

# The NURBS Book Ex9.1
points = ((0, 0), (3, 4), (-1, 4), (-4, 0), (-4, -3))
degree = 3  # cubic curve

# Do global curve interpolation
curve = fitting.interpolate_curve(points, degree)

# Plot the interpolated curve
curve.delta = 0.01
curve.vis = vis.VisCurve2D()
curve.render()

# # Visualize data and evaluated points together
# import numpy as np
# import matplotlib.pyplot as plt
# evalpts = np.array(curve.evalpts)
# pts = np.array(points)
# plt.plot(evalpts[:, 0], evalpts[:, 1])
# plt.scatter(pts[:, 0], pts[:, 1], color="red")
# plt.show()
Пример #17
0
def get_cm_from_interpolation_length(pts, interpolation_factor, center_circle,
                                     radius):  # 0 is circ
    center = center_circle
    cm = multi.CurveContainer()
    cm.vis = VisMPL.VisCurve2D(axes=False,
                               labels=False,
                               ctrlpts=False,
                               legend=False)
    circle_length = 2 * math.pi * radius
    tangents = []
    curve_lengths = []
    for i in range(len(pts)):
        p1 = pts[(i - 1) % len(pts)]
        p2 = pts[(i + 1) % len(pts)]
        pr = (p2[0] - p1[0], p2[1] - p1[1])
        alpha = math.atan2(pr[1], pr[0]) % math.pi
        tangents.append(alpha)

    dists = []
    for i in range(len(pts)):
        dist = functions.euclid_dist(pts[i], pts[(i + 1) % len(pts)])
        d = dist * 0.25
        dists.append(d)

    for i in range(len(pts)):
        c = BSpline.Curve()
        c.degree = 3
        d = dists[i]

        p1, p2 = get_points_on_tangent(pts[i], tangents[i], d)
        if functions.euclid_dist(
                p1, pts[(i + 1) % len(pts)]) < functions.euclid_dist(
                    p2, pts[(i + 1) % len(pts)]):
            p2, p1 = p1, p2

        p3, p4 = get_points_on_tangent(pts[(i + 1) % len(pts)],
                                       tangents[(i + 1) % len(pts)], d)

        if functions.euclid_dist(p4, pts[i]) < functions.euclid_dist(
                p3, pts[i]):
            p4, p3 = p3, p4

        c.ctrlpts = [pts[i], p2, p3, pts[(i + 1) % len(pts)]]
        c.knotvector = [0, 0, 0, 0, 1, 1, 1, 1]

        length = get_curve_length(c)
        curve_lengths.append(length)
        cm.add(c)

    curve_lengths.reverse()
    xc, yc = center_circle
    pts_r = list(pts)
    pts_r.reverse()
    distance_factor = circle_length / sum(curve_lengths)
    pts_interpolated = []
    starting_point = functions.project_to_circle(pts[0], center_circle, radius)
    pts_interpolated.append(starting_point)

    starting_angle = math.atan2(starting_point[1] - yc, starting_point[0] - xc)
    alpha = curve_lengths[0] * distance_factor / radius

    xp = xc + radius * math.cos(alpha)
    yp = yc + radius * math.sin(alpha)

    angle_sum = starting_angle
    for i in range(len(pts) - 1):
        alpha = curve_lengths[i] * distance_factor / radius
        angle_sum += alpha
        xp = xc + radius * math.cos(angle_sum)
        yp = yc + radius * math.sin(angle_sum)
        pts_interpolated.append((xp, yp))

    pts_interpolated.reverse()
    pts_interpolated.insert(0, pts_interpolated.pop())

    tangents_interpolated = []
    for i in range(len(pts_interpolated)):
        x, y = pts_interpolated[i]
        alpha = math.atan2(y - center_circle[1], x - center_circle[0])
        alpha -= 0.5 * math.pi
        alpha = alpha % math.pi
        tangents_interpolated.append(alpha)

    dists_interpolated = []
    for i in range(len(pts_interpolated)):
        x1, y1 = pts_interpolated[i]
        x4, y4 = pts_interpolated[(i + 1) % len(pts_interpolated)]
        xc, yc = center_circle
        axx = x1 - xc
        ay = y1 - yc
        bx = x4 - xc
        by = y4 - yc
        q1 = axx * axx + ay * ay
        q2 = q1 + axx * bx + ay * by
        k2 = 4 / 3 * (math.sqrt(2 * q1 * q2) - q2) / (axx * by - ay * bx)
        d = math.sqrt((k2 * ay)**2 + (k2 * axx)**2)
        dists_interpolated.append(d)

    cm = multi.CurveContainer()
    cm.vis = VisMPL.VisCurve2D(axes=False,
                               labels=False,
                               ctrlpts=False,
                               legend=False)
    pts = [[
        interpolation_factor * pp[0] + (1 - interpolation_factor) * pc[0],
        interpolation_factor * pp[1] + (1 - interpolation_factor) * pc[1]
    ] for (pp, pc) in zip(pts, pts_interpolated)]

    new_tangents = []
    for tp, tc in zip(tangents, tangents_interpolated):
        if abs(tp - tc) > math.pi / 2:
            if tp < math.pi / 2:
                t = interpolation_factor * (tp + math.pi) + (
                    1 - interpolation_factor) * tc
            elif tc < math.pi / 2:
                t = interpolation_factor * tp + (1 - interpolation_factor) * (
                    tc + math.pi)
        else:
            t = interpolation_factor * tp + (1 - interpolation_factor) * tc

        new_tangents.append(t)

    tangents = new_tangents

    dists = [
        interpolation_factor * dp + (1 - interpolation_factor) * dc
        for (dp, dc) in zip(dists, dists_interpolated)
    ]

    angle_mapping = {}

    ctrlpts = []
    for i in range(len(pts)):
        c = BSpline.Curve()
        c.degree = 3
        d = dists[i]

        p1, p2 = get_points_on_tangent(pts[i], tangents[i], d)

        if i == 0:
            print(tangents[i])
            if p1[1] < p2[1] and tangents[i] < math.pi:
                p1, p2 = p2, p1
            elif p1[1] > p2[1] and tangents[i] > math.pi:
                p1, p2 = p2, p1

        else:

            if math.atan2(p1[1] - center[1], p1[0] - center[0]) < math.atan2(
                    p2[1] - center[1], p2[0] - center[0]):
                p1, p2 = p2, p1
            if functions.euclid_dist(
                    p1, pts[(i + 1) % len(pts)]) < functions.euclid_dist(
                        p2, pts[(i + 1) % len(pts)]):
                p2, p1 = p1, p2

        xp, yp = pts[i]
        if (xp, yp) in angle_mapping:
            p = angle_mapping[(xp, yp)]

            if p[0] > xp and p2[0] > xp or p[0] < xp and p2[0] < xp:
                p1, p2 = p2, p1

        angle_mapping[(xp, yp)] = p2

        p3, p4 = get_points_on_tangent(pts[(i + 1) % len(pts)],
                                       tangents[(i + 1) % len(pts)], d)

        if functions.euclid_dist(p4, pts[i]) < functions.euclid_dist(
                p3, pts[i]):
            p4, p3 = p3, p4

        xp, yp = pts[(i + 1) % len(pts)]
        angle_mapping[(xp, yp)] = p3

        c.ctrlpts = [pts[i], p2, p3, pts[(i + 1) % len(pts)]]
        c.knotvector = [0, 0, 0, 0, 1, 1, 1, 1]
        cm.add(c)

    return cm
Пример #18
0
n_cp = 10
radius_x = 5
radius_y = 10
n_sp = 100
degree = 3

sp = np.array([[radius_x * math.cos(t), radius_y * math.sin(t)]
               for t in np.linspace(0, 2 * math.pi, n_sp)])
t = np.linspace(0, 1, n_sp)

# plt.scatter(sp[:,0], sp[:,1])
# plt.show()

n_knot = n_cp + degree + 1
# knot = np.linspace(0,1, n_knot).tolist()
knot = generate(degree, n_cp)

A = np.array([[basis_function_one(degree, knot, j, t[i]) for j in range(n_cp)]
              for i in range(n_sp)])
print(A.shape)

invATA = np.linalg.inv(np.dot(A.T, A))
cp = np.dot(np.dot(invATA, A.T), sp).tolist()

crv = BSpline.Curve()
crv.degree = degree
crv.ctrlpts = cp

crv.knotvector = knot
crv.vis = VisMPL.VisCurve2D()
crv.render()
Пример #19
0
    q1 = ax * ax + ay * ay
    q2 = q1 + ax * bx + ay * by
    k2 = 4 / 3 * (math.sqrt(2 * q1 * q2) - q2) / (ax * by - ay * bx)

    x2 = xc + ax - k2 * ay
    y2 = yc + ay + k2 * ax
    x3 = xc + bx + k2 * by
    y3 = yc + by - k2 * bx

    return 0, (x2, y2), (x3, y3)


curve = NURBS.Curve()
mcrv_circle = multi.CurveContainer()
mcrv_circle.vis = VisMPL.VisCurve2D(axes=False,
                                    labels=False,
                                    ctrlpts=False,
                                    legend=False)
center = (317, 465)
#pts = [[204, 604], [284, 612], [387, 577], [485, 475], [430, 366], [325, 231], [274, 438], [193, 436], [150, 525], [204, 604], [284, 612], [387, 577]]
pts = [[204, 604], [284, 612], [387, 577], [485, 475], [430, 366], [325, 231],
       [274, 438], [193, 436], [150, 525], [204, 604]]
pts_c = [[204, 604], [284, 612], [387, 577], [485, 475], [430,
                                                          366], [325, 231],
         [274, 438], [193, 436], [150, 525], [204, 604], [284, 612],
         [387, 577]]
#pts = [[204, 604], [284, 612], [430, 366], [274, 438], [193, 436], [204, 604]]
#pts_c = [[204, 604], [284, 612], [430, 366], [274, 438], [193, 436], [204, 604], [284, 612], [430, 366]]
#radius = max([functions.euclid_dist(center, p) for p in pts])

curves_1 = []
curves_0 = []
Пример #20
0
    k2 = 4 / 3 * (math.sqrt(2 * q1 * q2) - q2) / (ax * by - ay * bx)

    x2 = xc + ax - k2 * ay
    y2 = yc + ay + k2 * ax
    x3 = xc + bx + k2 * by
    y3 = yc + by - k2 * bx

    return 0, (x2, y2), (x3, y3)


#pts = [[204, 604], [284, 612], [387, 577], [485, 475], [430, 366], [325, 231], [274, 438], [193, 436], [150, 525], [204, 604], [284, 612], [387, 577]]
pts = [[485, 475], [430, 366], [325, 231], [274, 438], [193, 436], [150, 525],
       [204, 604], [284, 612], [387, 577]]
cm = multi.CurveContainer()
cm.vis = VisMPL.VisCurve2D(axes=False,
                           labels=False,
                           ctrlpts=True,
                           legend=False)

x = [p[0] for p in pts]
y = [p[1] for p in pts]

# append the starting x,y coordinates
x = np.r_[x, x[0]]
y = np.r_[y, y[0]]

# fit splines to x=f(u) and y=g(u), treating both as periodic. also note that s=0
# is needed in order to force the spline fit to pass through all the input points.
tck, u = interpolate.splprep([x, y], s=0, per=True)

knots = list(tck[0])
coeff = list(tck[1])
Пример #21
0
# Set up the curve
test_c.degree = degree
test_c.ctrlpts = CP
# test_c.ctrlpts = exchange.import_txt("ex_curve02.cpt")

test_c.knotvector = U
# Auto-generate knot vector
# test_c.knotvector = utilities.generate_knot_vector(test_c.degree, len(test_c.ctrlpts))
# Set evaluation delta
test_c.delta = 0.01

# Evaluate curve in same points as the
test_c.evaluate()
# Plot the control point polygon and the evaluated curve
vis_comp = vis.VisCurve2D()
test_c.vis = vis_comp
# test_c.render()


# Evaluate derivatives at u = 0.6
ders1 = test_c.derivatives(0.6, 4)

# plot the first derivative, normed, at correct location.
fig = plt.figure(num=1)
plt.plot([ders1[0][0], ders1[0][0] + ders1[1][0]], [ders1[0][1], ders1[0][1] + ders1[1][1]], 'k')  # First derivative
plt.plot([ders1[0][0], ders1[0][0] + ders1[2][0]], [ders1[0][1], ders1[0][1] + ders1[2][1]], 'r')  # Second derivative
# plt.show()

pdb.set_trace()
# Adapt nurb from B-spline curve
Пример #22
0
# Create a NURBS curve instance (full circle)
curve = NURBS.Curve()

# Set up curve
curve.degree = 2
curve.ctrlptsw = exchange.import_txt("ex_curve04.cptw")

# Use a specialized knot vector
curve.knotvector = [0, 0, 0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1, 1, 1]

# Set evaluation delta
curve.delta = 0.01

# Evaluate curve
curve.evaluate()

# Plot the control point polygon and the evaluated curve
curve.vis = VisMPL.VisCurve2D()
curve.render()

# Degree elevation
operations.degree_operations(curve, [1])
curve.render()

# Degree reduction
operations.degree_operations(curve, [-1])
curve.render()

# Good to have something here to put a breakpoint
pass
Пример #23
0
curve1.delta = 0.01

# Set up the Bezier curve
curve1.ctrlpts = [[10, 0], [15, 15], [20, 0]]
curve1.degree = 2

# Auto-generate knot vector
curve1.knotvector = utilities.generate_knot_vector(curve1.degree,
                                                   len(curve1.ctrlpts))

# Evaluate curve
curve1.evaluate()

# Draw the control point polygon and the evaluated curve
if render_curve:
    vis_comp1 = VisMPL.VisCurve2D()
    curve1.vis = vis_comp1
    curve1.render()

#
# 2D CURVE 2
#

# Create another B-Spline curve instance (Bezier Curve)
curve2 = BSpline.Curve2D()

# Set evaluation delta
curve2.delta = 0.01

# Set up the Bezier curve
curve2.ctrlpts = [[10, 0], [15, 15], [15, 15], [20, 0]]
Пример #24
0
 def run(self, N, weight):
     cv = Multi.MultiCurve()
     cv.add(self.create_bezie_curve(self.lst[0], self.lst[1], self.lst[2], weight))
     vis_compl = VisMPL.VisCurve2D()
     cv.vis = vis_compl
     cv.render()
Пример #25
0
def get_cm_from_interpolation_radial(pts, interpolation_factor):  # 0 is circ
    center_circle = (200, 540)
    center_polygon = (223, 555)
    center = center_circle[0] * (
        1 - interpolation_factor
    ) + center_polygon[0] * interpolation_factor, center_circle[1] * (
        1 - interpolation_factor) + center_polygon[1] * interpolation_factor
    radius = 70
    tangents = []
    for i in range(len(pts)):
        p1 = pts[(i - 1) % len(pts)]
        p2 = pts[(i + 1) % len(pts)]
        pr = (p2[0] - p1[0], p2[1] - p1[1])
        alpha = math.atan2(pr[1], pr[0])
        tangents.append(alpha)

    dists = []
    for i in range(len(pts)):
        dist = functions.euclid_dist(pts[i], pts[(i + 1) % len(pts)])
        d = dist * 0.3
        dists.append(d)

    pts_interpolated = [
        functions.project_to_circle(p, center_circle, radius) for p in pts
    ]
    tangents_interpolated = []
    for i in range(len(pts)):
        x, y = pts[i]
        alpha = math.atan2(y - center_circle[1], x - center_circle[0])
        alpha -= 0.5 * math.pi
        alpha = alpha % math.pi
        tangents_interpolated.append(alpha)

    dists_interpolated = []
    for i in range(len(pts_interpolated)):
        x1, y1 = pts_interpolated[i]
        x4, y4 = pts_interpolated[(i + 1) % len(pts_interpolated)]
        xc, yc = center_circle
        axx = x1 - xc
        ay = y1 - yc
        bx = x4 - xc
        by = y4 - yc
        q1 = axx * axx + ay * ay
        q2 = q1 + axx * bx + ay * by
        k2 = 4 / 3 * (math.sqrt(2 * q1 * q2) - q2) / (axx * by - ay * bx)
        d = math.sqrt((k2 * ay)**2 + (k2 * axx)**2)
        dists_interpolated.append(d)

    cm = multi.CurveContainer()
    cm.vis = VisMPL.VisCurve2D(axes=False,
                               labels=False,
                               ctrlpts=False,
                               legend=False)
    pts = [[
        interpolation_factor * pp[0] + (1 - interpolation_factor) * pc[0],
        interpolation_factor * pp[1] + (1 - interpolation_factor) * pc[1]
    ] for (pp, pc) in zip(pts, pts_interpolated)]

    new_tangents = []
    for tp, tc in zip(tangents, tangents_interpolated):
        if abs(tp - tc) > math.pi / 2:
            if tp < math.pi / 2:
                t = interpolation_factor * (tp + math.pi) + (
                    1 - interpolation_factor) * tc
            elif tc < math.pi / 2:
                t = interpolation_factor * tp + (1 - interpolation_factor) * (
                    tc + math.pi)
        else:
            t = interpolation_factor * tp + (1 - interpolation_factor) * tc

        new_tangents.append(t)

    tangents = new_tangents

    dists = [
        interpolation_factor * dp + (1 - interpolation_factor) * dc
        for (dp, dc) in zip(dists, dists_interpolated)
    ]

    ctrlpts = []
    for i in range(len(pts)):
        c = BSpline.Curve()
        c.degree = 3
        d = dists[i]

        p1, p2 = get_points_on_tangent(pts[i], tangents[i], d)
        if math.atan2(p1[1] - center[1], p1[0] - center[0]) < math.atan2(
                p2[1] - center[1], p2[0] - center[0]):
            p1, p2 = p2, p1
        if functions.euclid_dist(
                p1, pts[(i + 1) % len(pts)]) < functions.euclid_dist(
                    p2, pts[(i + 1) % len(pts)]):
            p2, p1 = p1, p2

        p3, p4 = get_points_on_tangent(pts[(i + 1) % len(pts)],
                                       tangents[(i + 1) % len(pts)], d)

        if functions.euclid_dist(p4, pts[i]) < functions.euclid_dist(
                p3, pts[i]):
            p4, p3 = p3, p4

        c.ctrlpts = [pts[i], p2, p3, pts[(i + 1) % len(pts)]]
        c.knotvector = [0, 0, 0, 0, 1, 1, 1, 1]
        cm.add(c)

    return cm
Пример #26
0
# curve1.knotvector = (0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 5.0, 5.0)
# curve2.ctrlpts =[(disp_X[2,0], -disp_Z[2,0]),
#                 (disp_X[2,1], -disp_Z[2,1]),
#                 (disp_X[2,2], -disp_Z[2,2]),
#                 (disp_X[2,3], -disp_Z[2,3]),
#                 (disp_X[2,4], -disp_Z[2,4]),
#                 (disp_X[2,5], -disp_Z[2,5]),
#                 (disp_X[2,6], -disp_Z[2,6]),
#                 (disp_X[2,7], -disp_Z[2,7]),]
# curve2.knotvector = (0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 5.0, 5.0)

# multi_curve_x = Multi.MultiCurve(curve0, curve1, curve2)

multi_curve.delta = 0.05
vis_config = VisMPL.VisConfig(legend=False)
multi_curve.vis = VisMPL.VisCurve2D(vis_config)
multi_curve.render()

print("Prozes time:  %s seconds ---" % (time.time() - start_time))
print("Exit!")

# print('Kontrollpunkte und Gewichte:')

# for i in range(curve_geometry.NbPoles):
#     pole = curve_geometry.Pole(i)
#     weight = curve_geometry.Weight(i)

#     print('  ', i, pole, weight)

# print()
# print('Knots:')
    def smooth_bspline(self, filename):
        """
        Smooth respiratory function using B-spline curve

        Parameters
        ----------
        filname: string
            Name of 2DST file to smooth the respiratory function

        Returns
        -------
        snake: list
            Optimised B-spline curve (respiratory function smoothed)
        """

        # Recover respiratory function extracted from 2DST images using masks
        ldiaphragm_pts = [list(item) for item in self.respiratory_pattern(filename)]
        # print("Original diaphragm points: {}".format(ldiaphragm_pts))

        # img = cv2.imread('{}/{}/{}/{}'.format(DIR_2DST_DICOM, self.patient, self.plan, filename), 1)
        # diaphragm_mask = np.zeros((256, 50, 3), np.uint8)
        # img_mask = img.copy()
        # i = 0
        # while(i < len(ldiaphragm_pts) - 1):
        #     cv2.line(
        #         img_mask,
        #         ldiaphragm_pts[i], ldiaphragm_pts[i + 1],
        #         (255, 0, 0), 1)
        #     i = i + 1
        # cv2.imshow('Diaphragmatic level', img_mask)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
        # cv2.imwrite('name.png', img_mask)

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

        # Create a B-Spline curve instance
        curve = BSpline.Curve()

        # Set evaluation delta
        curve.delta = 0.0002

        """ Set up curve """
        # Set control points
        controlpts = ldiaphragm_pts
        convert_controlpts = map(lambda x: 255 - x[1], controlpts)
        for i in range(len(controlpts)):
            controlpts[i][1] = convert_controlpts[i]

        curve.ctrlpts = controlpts

        # Set curve degree
        curve.degree = 3

        # Auto-generate knot vector
        curve.knotvector =\
            utilities.generate_knot_vector(
                curve.degree, len(curve.ctrlpts))

        # Evaluate curve
        curve.evaluate()

        # Draw the control point polygon and the evaluated curve
        if render_curve:
            vis_comp = VisMPL.VisCurve2D()
            curve.vis = vis_comp
            curve.render()