Esempio n. 1
0
    def test_ssim(self):
        """Test ssim."""
        npt.assert_almost_equal(
            metrics.ssim(self.data1, self.data1**2),
            self.ssim_res,
            err_msg='Incorrect SSIM result',
        )

        npt.assert_almost_equal(
            metrics.ssim(self.data1, self.data1**2, mask=self.mask),
            self.ssim_mask_res,
            err_msg='Incorrect SSIM result',
        )

        npt.assert_raises(
            ValueError,
            metrics.ssim,
            self.data1,
            self.data1,
            mask=1,
        )
# undersample the k-space using a cartesian acquisition mask
# We then reconstruct the zero order solution as a baseline

# Get the locations of the kspace samples
kspace_loc = convert_mask_to_locations(mask.data)
# Generate the subsampled kspace
fourier_op = FFT(samples=kspace_loc, shape=image.shape)
kspace_data = fourier_op.op(image)

# Zero order solution
image_rec0 = pysap.Image(data=fourier_op.adj_op(kspace_data),
                         metadata=image.metadata)
# image_rec0.show()

# Calculate SSIM
base_ssim = ssim(image_rec0, image)
print(base_ssim)

#############################################################################
# FISTA optimization
# ------------------
#
# We now want to refine the zero order solution using a FISTA optimization.
# The cost function is set to Proximity Cost + Gradient Cost

# Setup the operators
linear_op = WaveletN(
    wavelet_name="sym8",
    nb_scales=4,
    dim=3,
    padding_mode="periodization",
Esempio n. 3
0
        mask = loadmat(samples_dirpath + path)
        mask = mask['samples']

        # Normalisation between [-0.5, 0.5[
        mask = mask / (2 * np.abs(mask).max())

        # means of metrics
        gamma_temp = [[], [], [], []]

        for j in range(X_train.shape[0]):
            image = X_train[j]
            img_recons, cost = g(image, mask, **kwargs)
            m = np.array([
                snr(image, img_recons),
                psnr(image, img_recons),
                ssim(image, img_recons, None),
                nrmse(image, img_recons)
            ])

            print('ID img, decay, tau, recons metric: ({}, {}, {},'
                  '{})\n'.format(j, decay, tau, m))
            # gamma_temp = gamma_temp + m
            for i in range(len(m)):
                gamma_temp[i].append(m[i])

            cnt += 1
            print('PROGRESSION: {:4f}%\n'.format(
                (cnt * 100) / (len(decays) * len(taus) * X_train.shape[0])))

        # Save metrics and data of the reconstructions
        res_dict['mean_snr'] = np.mean(gamma_temp[0])
    atol=1e-4,
    verbose=1,
    get_cost=True)
imshow3D(np.abs(x_final), display=True)


plt.figure()
plt.plot(cost)
plt.show()

print('Saving the cube')
np.save('/volatile/bsarthou/datas/XP_pysap/save_FISTA_300_sym8_mu5e-6.npy', x_final)

ref = np.load('/volatile/bsarthou/datas/XP_pysap/ref_Ipat4.npy')

print('SSIM iPAT4:', ssim(mat2gray(ref), mat2gray(x_final), mask=None))

#
# #############################################################################
# # Condata-Vu optimization
# # -----------------------
# #
# # We now want to refine the zero order solution using a Condata-Vu
# # optimization.
# # Here no cost function is set, and the optimization will reach the
# # maximum number of iterations. Fill free to play with this parameter.
#
# # Start the CONDAT-VU reconstruction
# max_iter = 1
# gradient_op_cd = Gradient_pMRI(data=kspace_data,
#                                fourier_op=fourier_op,
fourier_op = NonCartesianFFT(
    samples=kspace_loc,
    shape=image.shape,
    implementation='gpuNUFFT',
)
fourier_op_density_comp = NonCartesianFFT(
    samples=kspace_loc,
    shape=image.shape,
    implementation='gpuNUFFT',
    density_comp=density_comp
)
# Get the kspace data retrospectively. Note that this can be done with
# `fourier_op_density_comp` as the forward operator is the same
kspace_obs = fourier_op.op(image.data)

# Simple adjoint
image_rec0 = pysap.Image(data=np.abs(fourier_op.adj_op(kspace_obs)))
# image_rec0.show()
base_ssim = ssim(image_rec0, image)
print('The SSIM from Adjoint is : ' + str(base_ssim))

# Density Compensation adjoint:
# This preconditions k-space giving a result closer to inverse
image_rec1 = pysap.Image(data=np.abs(
    fourier_op_density_comp.adj_op(kspace_obs))
)
# image_rec1.show()
new_ssim = ssim(image_rec1, image)
print('The SSIM from Density '
      'compensated Adjoint is : ' + str(new_ssim))
Esempio n. 6
0
def pdhg(data, p, **kwargs):
    # --
    # -- MAIN LOWER LEVEL FUNCTION
    # --
    # INPUTS: - data: kspace measurements
    #         - p: p[:-1]=subsampling mask S(p), p[-1]=regularisation parameter alpha(p)
    #                   So len(p)=len(data)+1
    #         - fourier_op: fourier operator from a full mask of same shape as the final image.
    #         - linear_op: linear operator used in regularisation functions
    #                      For the moment, only use waveletN.
    #         - param: lower level energy parameters
    #                  Must contain parameters keys "epsilon" and "gamma".
    #           mask_type (optional): type of mask used ("cartesian", "radial"). Assume a cartesian mask if not given.
    # --
    # OPTIONAL INPUTS:
    #         - const: algorithm constants if we already know the values we want to use for tau and sigma
    #                  If not given, will compute them according to what is said in the article.
    #         - compute_energy: bool, we compute and return energy over iterations if True (default: False)
    #         - ground_truth: matrix representing the true image the data come from (default: None). If not None, we compute the ssim over iterations.
    #         - maxit,tol: We stop the algorithm when the norm of the difference between two steps
    #                      is smaller than tol or after maxit iterations (default: 200, 1e-4)
    # --
    # OUTPUTS: - uk: final image
    #          - norms(, energy, ssims): evolution of stopping criterion (and energy if compute_energy is True / ssims if ground_truth not None)

    fourier_op = kwargs.get("fourier_op", None)
    linear_op = kwargs.get("linear_op", None)
    param = kwargs.get("param", None)

    # Create fourier_op and linear_op if not given for multithreading
    if fourier_op is None:
        samples = kwargs.get("samples", [])
        shape = kwargs.get("shape", ())
        if samples is not None:
            fourier_op = NonCartesianFFT(samples=samples,
                                         shape=shape,
                                         implementation='cpu')
    if fourier_op is None:
        raise ValueError("A fourier operator fourier_op must be given")
    if linear_op is None:
        wavelet_name = kwargs.get("wavelet_name", "")
        wavelet_scale = kwargs.get("wavelet_scale", 1)
        if wavelet_name != "":
            linear_op = WaveletN(wavelet_name=wavelet_name,
                                 nb_scale=wavelet_scale,
                                 padding_mode="periodization")
    if linear_op is None:
        raise ValueError("A linear operator linear_op must be given")

    if param is None: raise ValueError("Lower level parameters must be given")
    mask_type = kwargs.get("mask_type", "")

    const = kwargs.get("const", {})
    compute_energy = kwargs.get("compute_energy", False)
    ground_truth = kwargs.get("ground_truth", None)
    maxit = kwargs.get("maxit", 200)
    tol = kwargs.get("tol", 1e-6)
    verbose = kwargs.get("verbose", 1)

    #Global parameters
    p, pn1 = p[:-1], p[-1]
    epsilon = param["epsilon"]
    gamma = param["gamma"]
    n_iter = 0
    #Algorithm constants
    const = compute_constants(param, const, p)
    if verbose >= 0: print("Sigma:", const["sigma"], "\nTau:", const["tau"])

    #Initializing
    uk = fourier_op.adj_op(p * data)
    vk = np.copy(uk)
    wk = linear_op.op(uk)
    uk_bar = np.copy(uk)
    norm = 2 * tol

    #For plots
    if compute_energy:
        energy = []
    if ground_truth is not None:
        ssims = []
    norms = []

    #Main loop
    t1 = time.time()
    while n_iter < maxit and norm > tol:
        uk, vk, wk, uk_bar, norm = step(uk, vk, wk, uk_bar, const, p, pn1,
                                        data, param, linear_op, fourier_op,
                                        mask_type)
        n_iter += 1

        #Saving informations
        norms.append(norm)
        if compute_energy:
            energy.append(
                energy_wavelet(uk, p, pn1, data, gamma, epsilon, linear_op,
                               fourier_op))
        if ground_truth is not None:
            ssims.append(ssim(uk, ground_truth))

        #Printing
        if n_iter % 10 == 0 and verbose > 0:
            if compute_energy:
                print(n_iter, " iterations:\nCost:", energy[-1], "\nNorm:",
                      norm, "\n")
            else:
                print(n_iter, " iterations:\nNorm:", norm, "\n")
    if verbose >= 0:
        print("Finished in", time.time() - t1, "seconds.")

    #Return
    if compute_energy and ground_truth is not None:
        return uk, norms, energy, ssims
    elif ground_truth is not None:
        return uk, norms, ssims
    elif compute_energy:
        return uk, norms, energy
    else:
        return uk, norms
Esempio n. 7
0
def ssim_ssos(test, ref, mask=None):
    test = ssos(test)
    return ssim(test, ref, mask=mask)
Esempio n. 8
0
                                      lambda_init=1.0,
                                      max_nb_of_iter=max_iter,
                                      atol=1e-4,
                                      verbose=1,
                                      get_cost=False)

# print(np.abs(x_final))
imshow3D(np.abs(x_final), display=True)
# plt.figure()
# plt.plot(cost)
# plt.show()

np.save('/volatile/bsarthou/datas/save_baboon_128_NUFFT_cubic_GPU_sp3d.npy',
        x_final)
print('FISTA Mu:{} SSIM: {}'.format(
    mu, ssim(mat2grey(Iref), mat2grey(x_final), None)))
print('FISTA Mu:{} PSNR: {}'.format(
    mu, psnr(mat2grey(Iref), mat2grey(x_final), None)))

#
# gradient_op_cd = Gradient_pMRI(data=kspace_data,
#                                fourier_op=fourier_op)
# x_final, transform, cost = sparse_rec_condatvu(
#     gradient_op=gradient_op_cd,
#     linear_op=linear_op,
#     std_est=None,
#     std_est_method=None,
#     std_thr=2.,
#     mu=mu,
#     tau=None,
#     sigma=None,
Esempio n. 9
0
                                linear_op=linear_op)

        x_final, transform, cost = sparse_rec_fista(gradient_op=gradient_op,
                                                    linear_op=linear_op,
                                                    mu=0,
                                                    lambda_init=1.0,
                                                    max_nb_of_iter=max_iter,
                                                    atol=1e-4,
                                                    verbose=1,
                                                    get_cost=True)

        end = time.clock()

        tab_time[0, run] = end - start

        tab_metrics[0, run] = ssim(np.abs(Iref), np.abs(x_final), mask=None)
        tab_metrics[1, run] = snr(np.abs(Iref), np.abs(x_final), mask=None)
        tab_metrics[2, run] = psnr(np.abs(Iref), np.abs(x_final), mask=None)
        tab_metrics[3, run] = nrmse(np.abs(Iref), np.abs(x_final), mask=None)

        list_cost.append(cost)

else:

    for run in range(nb_runs):
        start = time.clock()

        if PWT:
            linear_op = pyWavelet3(wavelet_name=pwt_name, nb_scale=3)
        else:
            # import ipdb; ipdb.set_trace()