Exemplo n.º 1
0
    def test_option_save_best_reconstructor(self):
        dataset = get_standard_dataset('ellipses', impl='skimage')
        test_data = dataset.get_data_pairs('validation', 1)
        tt = TaskTable()
        fbp_reconstructor = FBPReconstructor(dataset.ray_trafo)
        hyper_param_choices = {'filter_type': ['Ram-Lak', 'Hann'],
                               'frequency_scaling': [0.1, 0.5, 1.0]}
        known_best_choice = {'filter_type': 'Hann',
                             'frequency_scaling': 0.5}
        path = 'dummypath'
        options = {'save_best_reconstructor': {'path': path,
                                               'measure': PSNR}}
        tt.append(fbp_reconstructor, test_data, measures=[PSNR],
                  hyper_param_choices=hyper_param_choices,
                  options=options)

        class ExtStringIO(StringIO):
            def __init__(self, ext, f, *args, **kwargs):
                self.ext = ext
                self.f = f
                super().__init__(*args, **kwargs)
                self.ext[self.f] = self.getvalue()

            def close(self):
                self.ext[self.f] = self.getvalue()
                super().close()
        ext = {}
        with patch('dival.reconstructors.reconstructor.open',
                   lambda f, *a, **kw: ExtStringIO(ext, f)):
            tt.run()
        self.assertIn(path + '_hyper_params.json', ext)
        self.assertDictEqual(json.loads(ext[path + '_hyper_params.json']),
                             known_best_choice)
Exemplo n.º 2
0
def fbp_reconstructor(dataset='ellipses', name=None):
    """
    :param dataset: Can be 'ellipses' or 'lodopab'
    :return: Filtered back projection reconstructor for the specified dataset
    """
    try:
        params = Params.load('{}_fbp'.format(dataset))
        standard_dataset = load_standard_dataset(dataset)
        if name is None:
            name = 'FBP'
        reconstructor = FBPReconstructor(standard_dataset.ray_trafo,
                                         hyper_params=params.dict,
                                         name=name)
        return reconstructor
    except Exception as e:
        raise Exception('The reconstructor doesn\'t exist')
Exemplo n.º 3
0
 def test(self):
     reco_space = odl.uniform_discr(
         min_pt=[-64, -64], max_pt=[64, 64], shape=[128, 128])
     phantom = odl.phantom.shepp_logan(reco_space, modified=True)
     geometry = odl.tomo.parallel_beam_geometry(reco_space, 30)
     ray_trafo = odl.tomo.RayTransform(reco_space, geometry, impl='skimage')
     proj_data = ray_trafo(phantom)
     observation = np.asarray(
         proj_data +
         np.random.normal(loc=0., scale=2., size=proj_data.shape))
     test_data = DataPairs(observation, phantom)
     tt = TaskTable()
     fbp_reconstructor = FBPReconstructor(ray_trafo, hyper_params={
         'filter_type': 'Hann',
         'frequency_scaling': 0.8})
     tt.append(fbp_reconstructor, test_data, measures=[PSNR, SSIM])
     tt.run()
     self.assertGreater(
         tt.results.results['measure_values'][0, 0]['psnr'][0], 15.)
Exemplo n.º 4
0
phantom = odl.phantom.shepp_logan(reco_space, modified=True)
ground_truth = phantom

geometry = odl.tomo.cone_beam_geometry(reco_space, 40, 40, 360)
ray_trafo = odl.tomo.RayTransform(reco_space, geometry, impl='astra_cpu')
proj_data = ray_trafo(phantom)
observation = (proj_data + np.random.poisson(0.3, proj_data.shape)).asarray()

test_data = DataPairs(observation, ground_truth, name='shepp-logan + pois')

# %% task table and reconstructors
eval_tt = TaskTable()

fbp_reconstructor = FBPReconstructor(ray_trafo,
                                     hyper_params={
                                         'filter_type': 'Hann',
                                         'frequency_scaling': 0.8
                                     })
cg_reconstructor = CGReconstructor(ray_trafo, reco_space.zero(), 4)
gn_reconstructor = GaussNewtonReconstructor(ray_trafo, reco_space.zero(), 2)
lw_reconstructor = LandweberReconstructor(ray_trafo, reco_space.zero(), 8)
mlem_reconstructor = MLEMReconstructor(ray_trafo, 0.5 * reco_space.one(), 1)

reconstructors = [
    fbp_reconstructor, cg_reconstructor, gn_reconstructor, lw_reconstructor,
    mlem_reconstructor
]
options = {'save_iterates': True}

eval_tt.append_all_combinations(reconstructors=reconstructors,
                                test_data=[test_data],
import numpy as np
from dival.evaluation import TaskTable
from dival.measure import PSNR, SSIM
from dival.reconstructors.odl_reconstructors import FBPReconstructor
from dival.datasets.standard import get_standard_dataset

np.random.seed(0)

# %% data
dataset = get_standard_dataset('ellipses', impl='astra_cpu')
test_data = dataset.get_data_pairs('test', 10)

# %% task table and reconstructors
eval_tt = TaskTable()

reconstructor = FBPReconstructor(dataset.ray_trafo)

eval_tt.append(reconstructor=reconstructor, measures=[PSNR, SSIM],
               test_data=test_data,
               hyper_param_choices={'filter_type': ['Ram-Lak', 'Hann'],
                                    'frequency_scaling': [0.8, 0.9, 1.]})

# %% run task table
results = eval_tt.run()
print(results.to_string(show_columns=['misc']))

# %% plot reconstructions
fig = results.plot_all_reconstructions(test_ind=range(1),
                                       fig_size=(9, 4), vrange='individual')
Exemplo n.º 6
0
from dival.reconstructors.odl_reconstructors import FBPReconstructor
from dival.datasets.standard import get_standard_dataset
from dival.util.constants import MU_MAX

# %% data
dataset = get_standard_dataset('lodopab', observation_model='pre-log')
ray_trafo = dataset.get_ray_trafo(impl='astra_cpu')
reco_space = ray_trafo.domain
test_data = dataset.get_data_pairs('test', 10)

# %% task table and reconstructors
eval_tt = TaskTable()

fbp_reconstructor = FBPReconstructor(
    ray_trafo, hyper_params={
        'filter_type': 'Hann',
        'frequency_scaling': 0.8},
    pre_processor=(-1/MU_MAX) * log_op(ray_trafo.range))

reconstructors = [fbp_reconstructor]

eval_tt.append_all_combinations(reconstructors=reconstructors,
                                test_data=[test_data])

# %% run task table
results = eval_tt.run()
results.apply_measures([PSNR, SSIM])
print(results)

# %% plot reconstructions
fig = results.plot_all_reconstructions(test_ind=range(3),
Exemplo n.º 7
0
parser.add_argument('--reg',
                    type=float,
                    default=10,
                    help='regularization weight on prior std. dev.')

args = parser.parse_args()

# %% [markdown]
# ### Load Data

# %%
# update dival config file with correct path to data
dival.config.set_config('/lodopab_dataset/data_path', args.path)

dataset = LoDoPaBDataset(observation_model=args.obsmodel, impl='astra_cpu')
fbp = FBPReconstructor(dataset.get_ray_trafo(impl='astra_cpu'))

# compute padded (height, width) for sinograms to ensure they are multiples of 32
height, width = dataset.shape[0]
input_height = (height // 32 + 1) * 32 + 256
input_width = (width // 32 + 1) * 32 + 256
#input_height = (height // args.crop + 1) * args.crop
#input_width = (width // args.crop + 1) * args.crop
#pad_bottom = input_height - height
#pad_right = input_width - width
hdiff = input_height - height
wdiff = input_width - width
pad_top = hdiff // 2
pad_left = wdiff // 2
pad_bottom = hdiff - hdiff // 2
pad_right = wdiff - wdiff // 2
Exemplo n.º 8
0
#     * Random access (by index) to the samples is not possible.
#       This is a general limitation of the generator-based implementation in
#       `dival.datasets.dataset.ObservationGroundTruthPairDataset`.
#       Since the samples are shuffled already, this would be fine for
#       training a network, but random access is desirable for other purposes.
#     * Simulating on the fly might be too slow.
#     * Potential irreproducibility, e.g. due to changes in used libraries.

# %% plot first three train images and fbp reconstructions
import matplotlib.pyplot as plt
from dival.util.plot import plot_images
from dival.measure import PSNR, SSIM
from dival.reconstructors.odl_reconstructors import FBPReconstructor
fbp_reconstructor = FBPReconstructor(dataset.ray_trafo,
                                     hyper_params={
                                         'filter_type': 'Hann',
                                         'frequency_scaling': 1.0
                                     })
for i, (obs, gt) in islice(enumerate(dataset.generator(part='train')), 3):
    reco = fbp_reconstructor.reconstruct(obs)
    reco = np.clip(reco, 0., 1.)
    _, ax = plot_images([reco, gt], fig_size=(10, 4))
    ax[0].figure.suptitle('train sample {:d}'.format(i))
    ax[0].set_title('FBP reconstruction')
    ax[1].set_title('Ground truth')
    psnr = PSNR(reco, gt)
    ssim = SSIM(reco, gt)
    ax[0].set_xlabel('PSNR: {:.2f}dB, SSIM: {:.3f}'.format(psnr, ssim))
    print('metrics for FBP reconstruction on sample {:d}:'.format(i))
    print('PSNR: {:.2f}dB, SSIM: {:.3f}'.format(psnr, ssim))
plt.show()
Exemplo n.º 9
0
# -*- coding: utf-8 -*-
import os
from tqdm import tqdm
from dival import get_standard_dataset
from dival.reconstructors.odl_reconstructors import FBPReconstructor

from lodopab_challenge.challenge_set import generator, NUM_IMAGES
from lodopab_challenge.submission import save_reconstruction, pack_submission

# define reconstructor
dataset = get_standard_dataset('lodopab')
reconstructor = FBPReconstructor(dataset.get_ray_trafo())
reconstructor.hyper_params['filter_type'] = 'Hann'
reconstructor.hyper_params['frequency_scaling'] = 0.641

# reconstruct and create submission
OUTPUT_PATH = '/localdata/lodopab_challenge_fbp'
os.makedirs(OUTPUT_PATH, exist_ok=True)
for i, obs in enumerate(tqdm(generator(), total=NUM_IMAGES)):
    reco = reconstructor.reconstruct(obs)
    save_reconstruction(OUTPUT_PATH, i, reco)

pack_submission(OUTPUT_PATH)