def compute_external():
    spl = initialize(50)
    img_r = create_RVSpine()
    st = timeit.default_timer()
    for i in range(10):
        compute_energy_external_total(spline=spl, img=img_r, nbr_dct=100)
    ed = timeit.default_timer()
    print ed - st
Exemplo n.º 2
0
    def cost(ctrl_pts):
        '''
        Compute the total energy given the new control points. It acts as the
        cost function of the optimisation.

        Parameters
        ----------
        ctrl_pts : numpy.ndarray
            The flattened vector of control points

        Returns
        -------
        ret: float
            The total energy corresponding to the given control points.

        '''
        ctrl_pts = np.array(ctrl_pts)
        ctrl_pts = np.reshape(ctrl_pts, ((len(ctrl_pts) / 2), 2))
        spline.set_ctrl_pts(ctrl_pts, only_free=True)
        ret = compute_energy_internal_total(spline=spline,
                                            ba_ratio=ba_ratio,
                                            nbr_dct=nbr) + \
            gamma * compute_energy_external_total(spline=spline,
                                                  img=img,
                                                  nbr_dct=nbr,
                                                  normalized=True)

        return ret
Exemplo n.º 3
0
    def cost(ctrl):
        ctrl = np.array(ctrl)
        ctrl = np.reshape(ctrl, ((len(ctrl) / 2), 2))
        spline.set_ctrl_pts(ctrl, only_free=True)

        return compute_energy_external_total(spline=spline, img=img,
                                             nbr_dct=10000,
                                             normalized=True) + \
            compute_energy_internal_total(spline=spline, nbr_dct=10000)
Exemplo n.º 4
0
 def cost(ctrl):
     ctrl = np.array(ctrl)
     ctrl = np.reshape(ctrl, ((len(ctrl) / 2), 2))
     spline.set_ctrl_pts(ctrl, only_free=True)
     if img is None:
         ret = compute_energy_internal_total(spline=spline, nbr_dct=1000)
     else:
         ret = compute_energy_internal_total(spline=spline,
                                             nbr_dct=1000) + \
                 gamma * compute_energy_external_total(spline=spline,
                                                       img=img,
                                                       nbr_dct=1000)
     return ret
Exemplo n.º 5
0
def compute_external(R):
    c = np.array([256, 256])
    n = 25
    phi = np.linspace(0, 2 * np.pi, n + 1)
    x_init = c[0] + R * np.cos(phi)
    y_init = c[1] + R * np.sin(phi)
    x_init[n] = x_init[0]
    y_init[n] = y_init[0]
    dat = np.array([x_init, y_init])
    tck, _ = splprep(dat, s=0, per=1, k=3)
    knots = tck[0]
    ctrl_pts = np.transpose(tck[1])
    deg = tck[2]
    spl = BSpline_periodic(knots, ctrl_pts, deg, is_periodic=True)
    img, imsh = create_vague()
    return compute_energy_external_total(spl, img=img)
Exemplo n.º 6
0
def changement_rayon_externe():
    # How the external energy changes with respect to the radius given that we
    # know the optimal radius
    n_dct = 1000
    img, imsh = create_image(30)
    R = np.linspace(20, 40, 100)
    energy = np.zeros(100)
    for i, dat in enumerate(R):
        spl = spline_initialize(dat)
        energy[i] = compute_energy_external_total(spline=spl, img=img,
                                                  nbr_dct=n_dct)
    fig = plt.figure()
    fig.canvas.set_window_title("Changement de rayon")
    plt.xlabel("Rayon")
    plt.ylabel("Energie")
    plt.plot(R, energy)
    plt.show()
Exemplo n.º 7
0
def changement_rayon_total():
    # How the total energy changes with respect to the radius given that we
    # know the optimal radius
    n_dct = 1000
    img, _ = create_image(30)
    R = np.linspace(20, 40, 1000)
    e_ext = np.zeros(1000)
    e_int = np.zeros(1000)
    e_total = np.zeros(1000)
    dict = {}
    gamma = 50
    for i, data in enumerate(R):
        spl = spline_initialize(data)
        e_int[i] = compute_energy_internal_total(spline=spl, ba_ratio=400,
                                                 nbr_dct=n_dct)
        e_ext[i] = compute_energy_external_total(spl, img, n_dct)
        e_total[i] = e_int[i] + gamma * e_ext[i]
        dict[data] = e_total[i]
    print min(dict.iteritems(), key=operator.itemgetter(1))[0]
    fig = plt.figure()
    fig.canvas.set_window_title("Rayon")
    ax = fig.add_subplot(111)
    ax1 = fig.add_subplot(311)
    ax2 = fig.add_subplot(312)
    ax3 = fig.add_subplot(313)
    ax1.title.set_text('Le changement avec gamma = ' + str(gamma))

    ax1.plot(R, e_int, 'r', label='Energie interne')
    ax1.legend(fontsize='large')
    ax2.plot(R, e_ext, 'g', label='Energie externe')
    ax2.legend(fontsize='large')
    ax3.plot(R, e_total, 'b', label='Energie totale')
    ax3.legend(fontsize='large')

    ax.spines['top'].set_color('none')
    ax.spines['bottom'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.spines['right'].set_color('none')
    ax.tick_params(labelcolor='w', top='off', bottom='off', left='off',
                   right='off')
    ax.set_xlabel('Rayon')
    ax.set_ylabel("Energie")
    plt.show()
Exemplo n.º 8
0
    def jacobian_spline_1side(dt_pts):
        '''
        Given the control point, this function helps to contruct the jacobian.
        It uses the property of spline to accelerate the computation.
            f'(x) = (f(x + h) - f(x)) / h.
        However, due to the use of normalisation in the external energy, we
        have to modify the formula. The detail is in the report (VI.G)

        Parameters
        ----------
        dt_pts : numpy.ndarray
            The vector of control point

        Returns
        -------
        ret : numpy.ndarray
            The jacobian matrix

        '''
        dt_pts = dt_pts.flatten()
        ctrl_pts = np.array(dt_pts)
        ctrl_pts = np.reshape(ctrl_pts, ((len(ctrl_pts) / 2), 2))
        spline.set_ctrl_pts(ctrl_pts, only_free=True)
        l1 = spline.get_length()
        e1t = compute_energy_external_total(spline, img, normalized=False)
        e1i = np.zeros(len(dt_pts) / 2)
        e1e = np.zeros(len(dt_pts) / 2)
        for i in range(len(dt_pts) / 2):
            e1i[i] = int_partial(spline, i)
            e1e[i] = ext_partial(spline, i)
        ret = np.zeros_like(dt_pts)
        dt_p = np.zeros_like(dt_pts)
        for i, data in enumerate(dt_pts):
            dt_p[:] = dt_pts
            dt_p[i] = data + eps
            ctrl = np.array(dt_p)
            ctrl = np.reshape(ctrl, ((len(ctrl) / 2), 2))
            spline.set_ctrl_pts(ctrl, only_free=True)
            l2 = spline.get_length()
            ret[i] = ((ext_partial(spline, i // 2) - e1e[i // 2] - e1t *
                       (l2 - l1) / l1) / l2 + int_partial(spline, i // 2) -
                      e1i[i // 2]) / eps
        return ret
Exemplo n.º 9
0
    def cost(ctrl_pts):
        '''
        Compute the total energy given the new control points. It is the cost
        function of the optimisation. It also helps to compute the traditional
        jacobian.

        Parameters
        ----------
        ctrl_pts : numpy.ndarray
            The flattened vector of control points

        Returns
        -------
        ret: float
            The total energy corresponding to the given control points.If
            img=None, it returns the partial internal energy. If not, it
            returns the partial total (internal + external) energy.

        '''
        ctrl_pts = np.array(ctrl_pts)
        ctrl_pts = np.reshape(ctrl_pts, ((len(ctrl_pts) / 2), 2))
        spline.set_ctrl_pts(ctrl_pts, only_free=True)

        if img is None:
            ret = compute_energy_internal_total(spline=spline,
                                                ba_ratio=ba_ratio,
                                                nbr_dct=nbr)
        else:
            ret = compute_energy_internal_total(spline=spline,
                                                ba_ratio=ba_ratio,
                                                nbr_dct=nbr) + \
                    gamma * compute_energy_external_total(spline=spline,
                                                          img=img,
                                                          nbr_dct=nbr,
                                                          normalized=True)

        return ret
Exemplo n.º 10
0
def jacobian_spl_1_side_external(spline_o, img, gamma=1):
    '''
        Given the control point, this function helps to contruct the jacobian.
        It uses the property of spline to accelerate the computation.
            f'(x) = (f(x + h) - f(x)) / h.
        However, due to the use of normalisation in the external energy, we
        have to modify the formula. The detail is in the report (VI.G)

        Parameters
        ----------
        dt_pts : numpy.ndarray
            The vector of control point

        Returns
        -------
        ret : numpy.ndarray
            The jacobian matrix

    '''
    knots = spline_o.t
    deg = spline_o.k
    ctrl_pts = spline_o.get_ctrl_pts(only_free=True)
    nbr_lib = len(ctrl_pts) / 2
    n_total = 10000

    def ext_partial(spl, nth):
        if knots[nth] < 0:
            ust1 = 0.0
            ued1 = knots[nth + deg + 1]
            ust2 = knots[nth + nbr_lib]
            ued2 = 1.0
            n_dct1 = (ued1 - ust1) * n_total
            n_dct2 = (ued2 - ust2) * n_total
            n_dct1 = int(np.ceil(n_dct1))
            n_dct2 = int(np.ceil(n_dct2))
            return compute_energy_external_partial(spline=spl,
                                                   img=img,
                                                   ust=ust1, ued=ued1,
                                                   nbr_dct=n_dct1,
                                                   normalized=False) + \
                compute_energy_external_partial(spline=spl,
                                                img=img,
                                                ust=ust2, ued=ued2,
                                                nbr_dct=n_dct2,
                                                normalized=False)
        else:
            ust = knots[nth]
            ued = knots[nth + deg + 1]
            n_dct = (ued - ust) * n_total
            n_dct = int(np.ceil(n_dct))
            return compute_energy_external_partial(spline=spl,
                                                   img=img,
                                                   ust=ust,
                                                   ued=ued,
                                                   nbr_dct=n_dct,
                                                   normalized=False)

    def int_partial(spl, nth):
        if knots[nth] < 0:
            ust1 = 0
            ued1 = knots[nth + deg + 1]
            ust2 = knots[nth + nbr_lib]
            ued2 = 1.0
            n_dct1 = (ued1 - ust1) * n_total
            n_dct2 = (ued2 - ust2) * n_total
            n_dct1 = int(np.ceil(n_dct1))
            n_dct2 = int(np.ceil(n_dct2))
            ret1 = compute_energy_internal_partial(spline=spl,
                                                   ust=ust1, ued=ued1,
                                                   nbr_dct=n_dct1) + \
                compute_energy_internal_partial(spline=spl,
                                                ust=ust2, ued=ued2,
                                                nbr_dct=n_dct2)
            return ret1
        else:
            ust = knots[nth]
            ued = knots[nth + deg + 1]
            n_dct = (ued - ust) * n_total
            n_dct = int(np.ceil(n_dct))
            ret2 = compute_energy_internal_partial(spline=spl,
                                                   ust=ust,
                                                   ued=ued,
                                                   nbr_dct=n_dct)
            return ret2

    spline = copy.deepcopy(spline_o)
    ctrl_pts = spline.get_ctrl_pts(only_free=True)
    dat = ctrl_pts.flatten()
    mat = np.zeros_like(dat)
    eps = 10.0**-5.0
    dat_p = np.zeros_like(dat)
    e1e = np.zeros(len(ctrl_pts))
    e1i = np.zeros(len(ctrl_pts))
    l1 = spline.get_length()
    e1t = compute_energy_external_total(spline=spline,
                                        img=img,
                                        normalized=False)

    for i in range(len(e1e)):
        e1e[i] = ext_partial(spline, i)
        e1i[i] = int_partial(spline, i)

    for i, data in enumerate(dat):
        dat_p[:] = dat
        dat_p[i] = data + eps
        ctrl = np.array(dat_p)
        ctrl = np.reshape(ctrl, ((len(ctrl) / 2), 2))
        spline.set_ctrl_pts(ctrl, only_free=True)
        e2e = ext_partial(spline, i // 2)
        l2 = spline.get_length()
        mat[i] = gamma * (e2e - e1e[i // 2] - e1t * (l2 - l1) / l1) / l2 / eps \
            + (int_partial(spline, i // 2) - e1i[i // 2]) / eps
    mat = mat.reshape((len(mat) / 2, 2))
    return mat
Exemplo n.º 11
0
def jacobian_spl_1_side(spline_o, img):
    '''
    Construct a external jacobian with simplified method
    
    Parameters
    ----------
    spline_o : BSpline_periodic
        A well-defined BSpline
    img: numpy.narray
        An image
    
    Returns
    -------
    mat : numpy.ndarray
        Matrix of jacobian
    '''
    knots = spline_o.t
    deg = spline_o.k
    ctrl_pts = spline_o.get_ctrl_pts(only_free=True)
    nbr_lib = len(ctrl_pts) / 2
    n_total = 10000

    def ext_partial(spl, nth):
        if knots[nth] < 0:
            ust1 = 0.0
            ued1 = knots[nth + deg + 1]
            ust2 = knots[nth + nbr_lib]
            ued2 = 1.0
            n_dct1 = (ued1 - ust1) * n_total
            n_dct2 = (ued2 - ust2) * n_total
            n_dct1 = int(np.ceil(n_dct1))
            n_dct2 = int(np.ceil(n_dct2))
            return compute_energy_external_partial(spline=spl,
                                                   img=img,
                                                   ust=ust1, ued=ued1,
                                                   nbr_dct=n_dct1,
                                                   normalized=False) + \
                        compute_energy_external_partial(spline=spl,
                                                        img=img,
                                                        ust=ust2, ued=ued2,
                                                        nbr_dct=n_dct2,
                                                        normalized=False)
        else:
            ust = knots[nth]
            ued = knots[nth + deg + 1]
            n_dct = (ued - ust) * n_total
            n_dct = int(np.ceil(n_dct))
            return compute_energy_external_partial(spline=spl,
                                                   img=img,
                                                   ust=ust,
                                                   ued=ued,
                                                   nbr_dct=n_dct,
                                                   normalized=False)

    def int_partial(spl, nth):
        if knots[nth] < 0:
            ust1 = 0
            ued1 = knots[nth + deg + 1]
            ust2 = knots[nth + nbr_lib]
            ued2 = 1.0
            n_dct1 = (ued1 - ust1) * n_total
            n_dct2 = (ued2 - ust2) * n_total
            n_dct1 = int(np.ceil(n_dct1))
            n_dct2 = int(np.ceil(n_dct2))
            ret1 = compute_energy_internal_partial(spline=spline,
                                                   ust=ust1, ued=ued1,
                                                   nbr_dct=n_dct1) + \
                compute_energy_internal_partial(spline=spline,
                                                ust=ust2, ued=ued2,
                                                nbr_dct=n_dct2)
            return ret1
        else:
            ust = knots[nth]
            ued = knots[nth + deg + 1]
            n_dct = (ued - ust) * n_total
            n_dct = int(np.ceil(n_dct))
            ret2 = compute_energy_internal_partial(spline=spline,
                                                   ust=ust,
                                                   ued=ued,
                                                   nbr_dct=n_dct)
            return ret2

    spline = copy.deepcopy(spline_o)
    ctrl_pts = spline.get_ctrl_pts(only_free=True)
    dat = ctrl_pts.flatten()
    mat = np.zeros_like(dat)
    eps = 10.0**-5.0
    dat_p = np.zeros_like(dat)
    e1e = np.zeros(len(ctrl_pts))
    e1i = np.zeros(len(ctrl_pts))
    l1 = spline.get_length()
    e1t = compute_energy_external_total(spline=spline,
                                        img=img,
                                        normalized=False)

    for i in range(len(e1e)):
        e1e[i] = ext_partial(spline, i)
        e1i[i] = int_partial(spline, i)

    for i, data in enumerate(dat):
        dat_p[:] = dat
        dat_p[i] = data + eps
        ctrl = np.array(dat_p)
        ctrl = np.reshape(ctrl, ((len(ctrl) / 2), 2))
        spline.set_ctrl_pts(ctrl, only_free=True)
        e2e = ext_partial(spline, i // 2)
        l2 = spline.get_length()
        mat[i] = (e2e - e1e[i // 2] - e1t * (l2 - l1) / l1) / l2 / eps + \
            (int_partial(spline, i // 2) - e1i[i // 2]) / eps
    mat = mat.reshape((len(mat) / 2, 2))
    return mat