Пример #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)
Пример #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)
Пример #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)
Пример #4
0
class PdRecon(object):
    """
    A Reconstruction object to solve regularized inverse reconstruction problems.
    Solver is Primal-Dual based.
    Form:
        1/2 * ||O*x - f||^2 + \alpha J(x)

        with Operator O : X -> Y
        J(x) regularisation term
    """
    def __init__(self,
                 O: LinearOperator,
                 domain_shape: np.ndarray,
                 reg_mode: str = '',
                 alpha: float = 0.01,
                 tau: float = None):
        self._reg_mode = None

        self.O = O
        self.domain_shape = domain_shape
        self.alpha = alpha
        self.tau = tau
        self.reg_mode = reg_mode
        self.solver = None

    @property
    def reg_mode(self):
        return self._reg_mode

    @reg_mode.setter
    def reg_mode(self, value):
        if value in ['tikhonov', 'tv', None]:
            self._reg_mode = value
        else:
            msg = "Please use reg_mode out of ['tikhonov', 'tv', '']"
            raise ValueError(msg)

    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)
Пример #5
0
class PdSmooth(object):
    """
    A Reconstruction object to solve regularized inverse reconstruction problems.
    Solver is Primal-Dual based.
    Form:
        1/2 * ||x - f||^2 + \alpha J(x)

        J(x) regularisation term J in [TV(), || ||]
    """
    def __init__(self,
                 domain_shape: np.ndarray,
                 reg_mode: str = '',
                 alpha=0.01,
                 tau: float = None):
        self._reg_mode = None

        self.domain_shape = domain_shape
        self.alpha = alpha
        self.tau = tau
        self.reg_mode = reg_mode
        self.solver = None

        if type(alpha) is not float:
            if self.alpha.shape == domain_shape:
                self.alpha = Diagonal(self.alpha.ravel())
            else:
                msg = "shape of local parameter alpha does not match: "+ \
                      str(self.alpha.shape) + "!=" + str(domain_shape)
                raise ValueError(msg)

    @property
    def reg_mode(self):
        return self._reg_mode

    @reg_mode.setter
    def reg_mode(self, value):
        if value in ['tikhonov', 'tv', None]:
            self._reg_mode = value
        else:
            msg = "Please use reg_mode out of ['tikhonov', 'tv', '']"
            raise ValueError(msg)

    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 = grad * self.alpha

            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 = 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)
Пример #6
0
def multi_class_segmentation_bregman(img,
                                     classes: list,
                                     beta: float = 0.001,
                                     delta: float = 1,
                                     qk=None,
                                     tau: float = None):

    f = np.zeros(((img.shape[0], img.shape[1], len(classes))))
    raveld_f = np.zeros(((img.shape[0] * img.shape[1], len(classes))))

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

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

    shape = (img.shape[0], img.shape[1])

    ex = np.ones((shape[1], 1))
    ey = np.ones((1, shape[0]))
    dx = sparse.diags([1, -1], [0, 1], shape=(shape[1], shape[1])).tocsr()
    dx[shape[1] - 1, :] = 0
    dy = sparse.diags([-1, 1], [0, 1], shape=(shape[0], shape[0])).tocsr()
    dy[shape[0] - 1, :] = 0

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

    #grad = sparse.hstack([grad, sparse.csr_matrix( (grad.shape[0], grad.shape[1]), dtype=int)])

    #gradT = sparse.block_diag([grad.T]*len(classes))

    #grad = sparse.vstack([grad]*len(classes))

    samp_values = f.shape[0]  #np.prod(np.shape(f))

    boundaries = 'neumann'
    # 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)
    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 = 150

    solver.tol = 10**(-6)

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

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

    # set(figure,'defaulttextinterpreter','latex');
    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

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

    return result0, result
Пример #7
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)
Пример #8
0
class PdSmooth(object):
    """
    A Reconstruction object to solve regularized inverse reconstruction problems.
    Solver is Primal-Dual based.
    Form:
        1/2 * ||x - f||^2 + \alpha J(x)

        J(x) regularisation term J in [TV(), || ||]
    """
    def __init__(self,
                 domain_shape: np.ndarray,
                 reg_mode: str = '',
                 alpha: float = 0.01,
                 tau: float = None):
        self._reg_mode = None

        self.domain_shape = domain_shape
        self.alpha = alpha
        self.tau = tau
        self.reg_mode = reg_mode
        self.solver = None

    @property
    def reg_mode(self):
        return self._reg_mode

    @reg_mode.setter
    def reg_mode(self, value):
        if value in ['tikhonov', 'tv', None]:
            self._reg_mode = value
        else:
            msg = "Please use reg_mode out of ['tikhonov', 'tv', '']"
            raise ValueError(msg)

    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)
Пример #9
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)
Пример #10
0
class PdSmoothBregman(object):
    """
    A Reconstruction object to solve regularized inverse reconstruction problems.
    Solver is Primal-Dual based.
    Form:
        1/2 * ||x - f||^2 + \alpha J(x)

        J(x) regularisation term
    """
    def __init__(self,
                 domain_shape: np.ndarray,
                 reg_mode: str = 'tv',
                 alpha: float = 1.1,
                 tau: float = None,
                 assessment: float = 1,
                 plot_iteration: bool = False,
                 data_output_path: str = ''):
        self._reg_mode = None

        self.domain_shape = domain_shape
        self.alpha = alpha
        self.tau = tau
        self.reg_mode = reg_mode
        self.solver = None
        self.plot_iteration = plot_iteration
        self.data_output_path = data_output_path
        self.assessment = assessment

    @property
    def reg_mode(self):
        return self._reg_mode

    @reg_mode.setter
    def reg_mode(self, value):
        if value in ['tv', None]:
            self._reg_mode = value
        else:
            msg = "Please use reg_mode out of ['tv', '']"
            raise ValueError(msg)

    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)
Пример #11
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
Пример #12
0
class PdReconBregman(object):
    """
    A Reconstruction object to solve regularized inverse reconstruction problems.
    Solver is Primal-Dual based.
    Form:
        1/2 * ||O*x - f||^2 + \alpha J(x)

        J(x) bregman regularisation term
    """

    def __init__(self,
                 O: LinearOperator,
                 domain_shape: np.ndarray,
                 reg_mode: str = 'tv',
                 alpha: float= 1.1,
                 tau: float = None,
                 assessment: float = 1,
                 plot_iteration: bool = False,
                 data_output_path: str = ''):
        self._reg_mode = None

        self.O = O
        self.domain_shape = domain_shape
        self.alpha = alpha
        self.tau = tau
        self.reg_mode = reg_mode
        self.solver = None
        self.plot_iteration = plot_iteration
        self.data_output_path = data_output_path
        self.assessment = assessment

    @property
    def reg_mode(self):
        return self._reg_mode

    @reg_mode.setter
    def reg_mode(self, value):
        if value in ['tv', None]:
            self._reg_mode = value
        else:
            msg = "Please use reg_mode out of ['tv', '']"
            raise ValueError(msg)

    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)
Пример #13
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