Beispiel #1
0
    def test_retained_energy(self):
        k = len(self.flat_array)
        x_zero = np.zeros(k)
        x_flat = np.ones(k)
        x_1d = np.ones(k).reshape(*self.d1_array.shape)
        x_2d = np.ones(k).reshape(*self.d2_array.shape)

        energy_const = 1/k * np.sum(self.flat_const_offset ** 2) * 100
        energy_noise = 1/k * np.sum(self.flat_noise ** 2) * 100

        # Integrity check of test setup
        self.assertGreater(energy_const, 1e-3)
        self.assertGreater(energy_noise, 1e-3)
        self.assertNotAlmostEqual(energy_const, energy_noise)

        # Identical arrays and zero case
        with self.assertRaises(ValueError):
            calculate_retained_energy(x_zero, x_zero)

        self.assertEqual(calculate_retained_energy(x_flat, x_flat), 100)
        self.assertEqual(calculate_retained_energy(x_flat, x_zero), 0)

        # Additve offset
        self.assertAlmostEqual(
            calculate_retained_energy(
                x_flat, self.flat_const_offset), energy_const)
        self.assertAlmostEqual(
            calculate_retained_energy(
                x_1d, self.d1_const_offset), energy_const)
        self.assertAlmostEqual(
            calculate_retained_energy(
                x_2d, self.d2_const_offset), energy_const)

        # Additive noise
        self.assertAlmostEqual(
            calculate_retained_energy(x_flat, self.flat_noise), energy_noise)
        self.assertAlmostEqual(
            calculate_retained_energy(x_1d, self.d1_noise), energy_noise)
        self.assertAlmostEqual(
            calculate_retained_energy(x_2d, self.d2_noise), energy_noise)

        # Fails
        self.assertNotAlmostEqual(
            calculate_retained_energy(x_flat, self.flat_noise), energy_const)
        self.assertNotAlmostEqual(
            calculate_mse(x_flat, self.flat_const_offset), energy_noise)
        with self.assertRaises(ValueError):
            calculate_retained_energy(x_zero, x_flat)
Beispiel #2
0
    def test_retained_energy(self):
        k = len(self.flat_array)
        x_zero = np.zeros(k)
        x_flat = np.ones(k)
        x_1d = np.ones(k).reshape(*self.d1_array.shape)
        x_2d = np.ones(k).reshape(*self.d2_array.shape)

        energy_const = 1/k * np.sum(self.flat_const_offset ** 2) * 100
        energy_noise = 1/k * np.sum(self.flat_noise ** 2) * 100

        # Integrity check of test setup
        self.assertGreater(energy_const, 1e-3)
        self.assertGreater(energy_noise, 1e-3)
        self.assertNotAlmostEqual(energy_const, energy_noise)

        # Identical arrays and zero case
        with self.assertRaises(ValueError):
            calculate_retained_energy(x_zero, x_zero)

        self.assertEqual(calculate_retained_energy(x_flat, x_flat), 100)
        self.assertEqual(calculate_retained_energy(x_flat, x_zero), 0)

        # Additve offset
        self.assertAlmostEqual(
            calculate_retained_energy(
                x_flat, self.flat_const_offset), energy_const)
        self.assertAlmostEqual(
            calculate_retained_energy(
                x_1d, self.d1_const_offset), energy_const)
        self.assertAlmostEqual(
            calculate_retained_energy(
                x_2d, self.d2_const_offset), energy_const)

        # Additive noise
        self.assertAlmostEqual(
            calculate_retained_energy(x_flat, self.flat_noise), energy_noise)
        self.assertAlmostEqual(
            calculate_retained_energy(x_1d, self.d1_noise), energy_noise)
        self.assertAlmostEqual(
            calculate_retained_energy(x_2d, self.d2_noise), energy_noise)

        # Fails
        self.assertNotAlmostEqual(
            calculate_retained_energy(x_flat, self.flat_noise), energy_const)
        self.assertNotAlmostEqual(
            calculate_mse(x_flat, self.flat_const_offset), energy_noise)
        with self.assertRaises(ValueError):
            calculate_retained_energy(x_zero, x_flat)
Beispiel #3
0
def show_psnr_energy_rolloff(img,
                             reconstructions,
                             fractions,
                             return_vals=False,
                             output_path=None,
                             fig_ext='pdf'):
    """
    Show the PSNR and energy rolloff for the reconstructions.

    A plot of the Peak Signal to Noise Ratio (PSNR) and retained energy in the
    `recontructions` versus the `fractions` of coefficients used in the
    reconstructions is shown. If return_vals is True, the data used in the plot
    is returned. If `output_path` is not None, the resulting figure and data
    used in the figure are saved.

    Parameters
    ----------
    img : ndarray
        The image which the reconstructions are based on.
    reconstructions : list or tuple
        The reconstructions (each an ndarray) to show rolloff for.
    fractions : list or tuple
        The fractions of coefficents used in the reconstructions.
    return_vals : bool
        The flag indicating wheter or not to return the PSNR and energy values
        (the default is False, which indicate that the values are not
        returned).
    output_path : str
        The output path (see notes below) to save the figure and data to (the
        default is None, which implies that the figure and data are not saved).
    fig_ext : str
        The figure extension determining the format of the saved figure (the
        default is 'pdf' which implies that the figure is saved as a PDF).

    Returns
    -------
    psnrs : ndarray
       The PSNR values shown in the figure (only returned if return_vals=True).
    energy : ndarray
       The retained energy values shown in the figure (only returned if
       return_vals=True).

    Notes
    -----
    The `output_path` is specified as a path to a folder + an optional prefix
    to the file name. The remaining file name is fixed. If e.g, the fixed part
    of the file name was 'plot', then:

    * output_path = '/home/user/' would save the figure under /home/user/ with
      the name plot.pdf.
    * output_path = '/home/user/best' would save the figure under /home/user
      with the name best_plot.pdf.

    In addition to the saved figures, an annotated and chased HDF database with
    the data used to create the figures are also saved. The name of the HDF
    database is the same as for the figure with the exception that the file
    extension is '.hdf5'.

    Examples
    --------
    Save a PSNR and energy rolloff plot for reconstructions bases on the DCT:

    >>> import os, numpy as np
    >>> from magni.imaging.dictionaries import analysis as _a
    >>> img = np.arange(64).astype(np.float).reshape(8, 8)
    >>> transform = 'DCT'
    >>> fractions = (0.2, 0.4)
    >>> coefs, recons = _a.get_reconstructions(img, transform, fractions)
    >>> o_p = './rolloff_test'
    >>> _a.show_psnr_energy_rolloff(img, recons, fractions, output_path=o_p)
    >>> current_dir = os.listdir('./')
    >>> for file in sorted(current_dir):
    ...     if 'rolloff_test' in file:
    ...         print(file)
    rolloff_test_psnr_energy_rolloff.hdf5
    rolloff_test_psnr_energy_rolloff.pdf

    """
    @_decorate_validation
    def validate_input():
        _numeric('img', ('integer', 'floating', 'complex'), shape=(-1, -1))
        _levels('reconstructions',
                (_generic(None, 'explicit collection'),
                 _numeric(None, ('integer', 'floating', 'complex'),
                          shape=img.shape)))
        _levels('fractions', (_generic(None, 'explicit collection'),
                              _numeric(None, 'floating', range_='[0;1]')))
        _numeric('return_vals', 'boolean')
        _generic('output_path', 'string', ignore_none=True)
        _generic('fig_ext', 'string')

    validate_input()

    psnrs = np.zeros_like(fractions)
    energy = np.zeros_like(fractions)

    for k, reconstruction in enumerate(reconstructions):
        psnrs[k] = _evaluation.calculate_psnr(img, reconstruction,
                                              float(img.max()))
        energy[k] = _evaluation.calculate_retained_energy(img, reconstruction)

    fig, axes = plt.subplots(1, 2)
    axes[0].plot(fractions, psnrs)
    axes[0].set_xlabel('Fraction of coefficients')
    axes[0].set_ylabel('PSNR [dB]')
    axes[1].plot(fractions, energy)
    axes[1].set_xlabel('Fraction of coefficients')
    axes[1].set_ylabel('Retained energy [%]')
    fig.suptitle(('PSNR/Energy vs. fraction of coefficients used in ' +
                  'reconstruction'),
                 fontsize=14)
    plt.tight_layout(rect=(0, 0, 1, 0.95))

    # Save figures and data
    if output_path is not None:
        datasets = {
            'psnrs': {
                'fractions': fractions,
                'values': psnrs
            },
            'energy': {
                'fractions': fractions,
                'values': energy
            }
        }
        _save_output(output_path, 'psnr_energy_rolloff', fig, fig_ext,
                     datasets)

    # Return values
    if return_vals:
        return psnrs, energy