Beispiel #1
0
    def solve(self, data: np.ndarray, maxiter: int = 150, tol: float = 5*10**(-4)):

        if self.reg_mode is not None:
            grad = Gradient(dims=self.domain_shape, edge = True, dtype='float64', kind='backward')
            K = self.alpha * grad
            if not self.tau:
                norm = np.abs(np.asscalar(K.eigs(neigs=1, which='LM')))
                sigma = 0.99 / norm
                print("Calced tau: "+str(sigma) + ". "
                      "Next run with same alpha, set this tau value to decrease runtime.")
                tau = sigma
            else:
                tau = self.tau
                sigma = tau
            if self.reg_mode == 'tv':
                F_star = Projection(self.domain_shape, len(self.domain_shape))
            else:
                F_star = DatatermLinear()
                F_star.set_proxdata(0)
        else:
            tau = 0.99
            sigma = tau
            F_star = DatatermLinear()
            K = 0

        G = DatatermRecBregman(self.O)
        G.set_proxparam(tau)
        G.set_proxdata(data.ravel())
        F_star.set_proxparam(sigma)

        pk = np.zeros(self.domain_shape)
        pk = pk.T.ravel()
        plt.Figure()
        ulast = np.zeros(self.domain_shape)
        u01 = ulast

        i = 0
        while np.linalg.norm(self.O * u01.ravel() - data.ravel()) > self.assessment:
            print("norm error: " + str(np.linalg.norm(self.O * u01.ravel() - data.ravel())))

            self.solver = PdHgm(K, F_star, G)
            self.solver.maxiter = maxiter
            self.solver.tol = tol

            G.set_proxdata(data.ravel())
            G.setP(pk)
            self.solver.solve()
            u01 = np.reshape(np.real(self.solver.var['x']), self.domain_shape)
            pk = pk - (1 / self.alpha) * np.real(self.O.H*(self.O*u01.ravel() - data.ravel()))
            i = i + 1
            if self.plot_iteration:
                plt.gray()
                plt.imshow(u01, vmin=0, vmax=1)
                plt.axis('off')
                #plt.title('RRE =' + str(round(RRE_breg, 2)), y=-0.1, fontsize=20)
                plt.savefig(self.data_output_path + 'Bregman_reconstruction_iter' + str(i) + '.png', bbox_inches='tight',
                            pad_inches=0)
                plt.close()

        return np.reshape(self.solver.var['x'], self.domain_shape)
Beispiel #2
0
    def solve(self,
              f: np.ndarray,
              maxiter: int = 150,
              tol: float = 5 * 10**(-4)):

        if self.reg_mode is not None:
            grad = Gradient(self.domain_shape,
                            edge=True,
                            dtype='float64',
                            kind='backward')
            K = self.alpha * grad

            if not self.tau:
                norm = np.abs(np.asscalar(K.eigs(neigs=1, which='LM')))
                sigma = 0.99 / norm
                tau = sigma
                print(
                    "Calced tau: " + str(sigma) + ". "
                    "Next run with same alpha, set this tau value to decrease runtime."
                )
            else:
                tau = self.tau
                sigma = tau

            if self.reg_mode == 'tv':
                F_star = Projection(self.domain_shape, len(self.domain_shape))
            else:
                F_star = DatatermLinear()
        else:
            tau = 0.99
            sigma = tau
            F_star = DatatermLinear()
            K = 0

        G = Dataterm(self.O)
        G.set_proxparam(tau)
        F_star.set_proxparam(sigma)
        self.solver = PdHgm(K, F_star, G)
        self.solver.maxiter = maxiter
        self.solver.tol = tol

        G.set_proxdata(f.ravel())
        self.solver.solve()

        return np.reshape(self.solver.var['x'], self.domain_shape)
Beispiel #3
0
    def solve(self,
              f: np.ndarray,
              maxiter: int = 150,
              tol: float = 5 * 10**(-4)):

        if self.reg_mode is not None:
            grad = Gradient(self.domain_shape, dtype='float64')
            K = self.alpha * grad

            if not self.tau:
                norm = np.abs(np.asscalar(K.eigs(neigs=1, which='LM')))
                sigma = 0.99 / norm
                tau = sigma
            else:
                tau = self.tau
                sigma = tau

            if self.reg_mode == 'tv':
                F_star = Projection(self.domain_shape, len(self.domain_shape))
            else:
                F_star = DatatermLinear()
        else:
            tau = 0.99
            sigma = tau
            F_star = DatatermLinear()
            K = 0

        G = Dataterm(self.O)
        G.set_proxparam(tau)
        F_star.set_proxparam(sigma)
        self.solver = PdHgm(K, F_star, G)
        self.solver.maxiter = maxiter
        self.solver.tol = tol

        G.set_proxdata(f.ravel())
        self.solver.solve()

        return np.reshape(self.solver.var['x'], self.domain_shape)
Beispiel #4
0
    def solve(self,
              data: np.ndarray,
              maxiter: int = 150,
              tol: float = 5 * 10**(-4)):

        if self.reg_mode is not None:
            if len(self.domain_shape) > 2:
                grad = Gradient(dims=self.domain_shape,
                                edge=True,
                                dtype='float64')
            else:
                ex = np.ones((self.domain_shape[1], 1))
                ey = np.ones((1, self.domain_shape[0]))
                dx = sparse.diags([1, -1], [0, 1],
                                  shape=(self.domain_shape[1],
                                         self.domain_shape[1])).tocsr()
                dx[self.domain_shape[1] - 1, :] = 0
                dy = sparse.diags([-1, 1], [0, 1],
                                  shape=(self.domain_shape[0],
                                         self.domain_shape[0])).tocsr()
                dy[self.domain_shape[0] - 1, :] = 0

                grad = sparse.vstack(
                    (sparse.kron(dx,
                                 sparse.eye(self.domain_shape[0]).tocsr()),
                     sparse.kron(sparse.eye(self.domain_shape[1]).tocsr(),
                                 dy)))

            K = self.alpha * grad
            if not self.tau:
                if np.prod(self.domain_shape) > 25000:
                    long = True
                else:
                    long = False
                if long:
                    print("Start evaluate tau. Long runtime.")
                if len(self.domain_shape) > 2:
                    norm = np.abs(np.asscalar(K.eigs(neigs=1, which='LM')))
                else:
                    norm = normest(K)
                sigma = 0.99 / norm
                if long:
                    print("Calc tau: " + str(sigma))
                tau = sigma
            else:
                tau = self.tau
                sigma = tau

            if self.reg_mode == 'tv':
                F_star = Projection(self.domain_shape, len(self.domain_shape))
            else:
                F_star = DatatermLinear()
                F_star.set_proxdata(0)
        else:
            tau = 0.99
            sigma = tau
            F_star = DatatermLinear()
            K = 0

        G = DatatermLinear()
        G.set_proxparam(tau)
        G.set_proxdata(data.ravel())
        F_star.set_proxparam(sigma)
        self.solver = PdHgm(K, F_star, G)
        self.solver.maxiter = maxiter
        self.solver.tol = tol
        self.solver.solve()

        return np.reshape(self.solver.var['x'], self.domain_shape)
Beispiel #5
0
    def solve(self,
              data: np.ndarray,
              maxiter: int = 150,
              tol: float = 5 * 10**(-4)):

        if self.reg_mode is not None:
            if len(self.domain_shape) > 2:
                grad = Gradient(dims=self.domain_shape,
                                edge=True,
                                dtype='float64')
            else:
                dx = sparse.diags([1, -1], [0, 1],
                                  shape=(self.domain_shape[1],
                                         self.domain_shape[1])).tocsr()
                dx[self.domain_shape[1] - 1, :] = 0
                dy = sparse.diags([-1, 1], [0, 1],
                                  shape=(self.domain_shape[0],
                                         self.domain_shape[0])).tocsr()
                dy[self.domain_shape[0] - 1, :] = 0

                grad = sparse.vstack(
                    (sparse.kron(dx,
                                 sparse.eye(self.domain_shape[0]).tocsr()),
                     sparse.kron(sparse.eye(self.domain_shape[1]).tocsr(),
                                 dy)))

            K = self.alpha * grad
            if not self.tau:
                if np.prod(self.domain_shape) > 25000:
                    long = True
                else:
                    long = False
                if long:
                    print("Start evaluate tau. Long runtime.")
                if len(self.domain_shape) > 2:
                    norm = np.abs(np.asscalar(K.eigs(neigs=1, which='LM')))
                else:
                    norm = normest(K)
                sigma = 0.99 / norm
                if long:
                    print("Calc tau: " + str(sigma))
                tau = sigma
            else:
                tau = self.tau
                sigma = tau

            if self.reg_mode == 'tv':
                F_star = Projection(self.domain_shape, len(self.domain_shape))
            else:
                F_star = DatatermLinear()
                F_star.set_proxdata(0)
        else:
            tau = 0.99
            sigma = tau
            F_star = DatatermLinear()
            K = 0

        G = DatatermLinearRecBregman()
        G.set_proxparam(tau)
        G.set_proxdata(data.ravel())
        F_star.set_proxparam(sigma)

        pk = np.zeros(self.domain_shape)
        pk = pk.T.ravel()
        plt.Figure()
        ulast = np.zeros(self.domain_shape)
        u01 = ulast
        i = 0

        while np.linalg.norm(u01.ravel() - data.ravel()) > self.assessment:
            print(np.linalg.norm(u01.ravel() - data.ravel()))
            print(self.assessment)

            self.solver = PdHgm(K, F_star, G)
            self.solver.maxiter = maxiter
            self.solver.tol = tol

            G.set_proxdata(data.ravel())
            G.setQ(pk)
            self.solver.solve()
            u01 = np.reshape(np.real(self.solver.var['x']), self.domain_shape)
            pk = pk - (1 / self.alpha) * (u01.ravel() - data.ravel())
            i = i + 1
            if self.plot_iteration:
                plt.gray()
                plt.imshow(u01, vmin=0, vmax=1)
                plt.axis('off')
                #plt.title('RRE =' + str(round(RRE_breg, 2)), y=-0.1, fontsize=20)
                plt.savefig(self.data_output_path +
                            'Bregman_reconstruction_iter' + str(i) + '.png',
                            bbox_inches='tight',
                            pad_inches=0)
                plt.close()

        return np.reshape(self.solver.var['x'], self.domain_shape)
Beispiel #6
0
def multi_class_segmentation(img,
                             classes: list,
                             beta: float = 0.001,
                             tau: float = None):

    raveld_f = np.zeros(((np.prod(img.shape), len(classes))))

    for i in range(len(classes)):
        raveld_f[:, i] = (img.ravel() - classes[i])**2

    f = raveld_f

    grad = pylops.Gradient(dims=img.shape,
                           edge=True,
                           dtype='float64',
                           kind="backward")
    K = beta * grad

    G = DatatermLinear()
    G.set_proxdata(f)
    F_star = Projection(f.shape, len(img.shape))
    solver = PdHgm(K, F_star, G)

    solver.var['x'] = np.zeros((K.shape[1], len(classes)))
    solver.var['y'] = np.zeros((K.shape[0], len(classes)))

    if tau:
        tau0 = tau
    else:
        norm = np.abs(np.asscalar(K.eigs(neigs=1, which='LM')))
        tau0 = 0.99 / norm
        print(
            "Calced tau: " + str(tau0) + ". "
            "Next run with same beta, set this tau value to decrease runtime.")
    sigma0 = tau0

    G.set_proxparam(tau0)
    F_star.set_proxparam(sigma0)
    solver.maxiter = 200
    solver.tol = 10**(-6)

    solver.solve()

    seg = np.reshape(solver.var['x'],
                     tuple(list(img.shape) + [len(classes)]),
                     order='C')

    a = seg
    result = []  #np.zeros(a.shape)
    #for i in range(a.shape[0]):  # SLOW
    #    for j in range(a.shape[1]):
    #            idx = np.argmin((a[i, j,  :]))
    #            result[i, j, idx] = 1
    tmp_result = np.argmin(a, axis=len(img.shape))

    for i, c in enumerate(classes):
        result.append((tmp_result == i).astype(int))

    result0 = sum([i * result[i] for i in range(len(classes))])

    result = np.array(result)

    return result0, result
Beispiel #7
0
def multi_class_segmentation(img,
                             classes: list,
                             beta: float = 0.001,
                             tau: float = None):

    #f = np.zeros( tuple( list(img.shape) + [len(classes)]))
    raveld_f = np.zeros(((np.prod(img.shape), len(classes))))

    for i in range(len(classes)):
        #f[:, :, i] = (img.T - classes[i]) ** 2
        raveld_f[:, i] = (img.ravel() - classes[i])**2

    #f = np.ravel(f, order='C')
    f = raveld_f

    grad = pylops.Gradient(dims=img.shape, dtype='float64')
    # grad = FirstDerivative(262144, boundaries=boundaries)
    K = beta * grad
    # vd1 = convex_segmentation(u0, beta0, classes)

    G = DatatermLinear()
    G.set_proxdata(f)
    F_star = Projection(f.shape, len(img.shape))
    solver = PdHgm(K, F_star, G)

    solver.var['x'] = np.zeros((K.shape[1], len(classes)))
    solver.var['y'] = np.zeros((K.shape[0], len(classes)))

    if tau:
        tau0 = tau
    else:
        tau0 = 0.99 / normest(K)
        print(tau0)
    sigma0 = tau0

    G.set_proxparam(tau0)
    F_star.set_proxparam(sigma0)
    solver.maxiter = 200
    solver.tol = 10**(-6)

    # G.set_proxdata(f)
    solver.solve()

    seg = np.reshape(solver.var['x'],
                     tuple(list(img.shape) + [len(classes)]),
                     order='C')

    a = seg
    result = []  #np.zeros(a.shape)
    #for i in range(a.shape[0]):  # SLOW
    #    for j in range(a.shape[1]):
    #            idx = np.argmin((a[i, j,  :]))
    #            result[i, j, idx] = 1
    tmp_result = np.argmin(a, axis=len(img.shape))

    for i, c in enumerate(classes):
        result.append((tmp_result == i).astype(int))

    result0 = sum([i * result[i] for i in range(len(classes))])

    result = np.array(result)

    return result0, result