PyWavelets - Wavelet Transforms in Python


PyWavelets - Wavelet Transforms in Python


PyWavelets is open source wavelet transform software for Python. It combines a simple high level interface with low level C and Cython performance.


Main features


The main features of PyWavelets are:
  • 1D, 2D and nD Forward and Inverse Discrete Wavelet Transform (DWT and IDWT)
  • 1D, 2D and nD Multilevel DWT and IDWT
  • 1D, 2D and nD Stationary Wavelet Transform (Undecimated Wavelet Transform)
  • 1D and 2D Wavelet Packet decomposition and reconstruction
  • 1D Continuous Wavelet Transform
  • Computing Approximations of wavelet and scaling functions
  • Over 100 built-in wavelet filters and support for custom wavelets
  • Single and double precision calculations
  • Real and complex calculations
  • Results compatible with Matlab Wavelet Toolbox (TM)

Installing

You can install PyWavelets with:
  • pip install PyWavelets
  • conda install pywavelets
Install juypter to use uss notebook:

pip install jupyter
jupyter notebook


Examples



import numpy as np
import matplotlib.pyplot as plt

import pywt # import the package
import pywt.data


# Load image
original = pywt.data.camera()

# Wavelet transform of image, and plot approximation and details
titles = ['Approximation', ' Horizontal detail',
          'Vertical detail', 'Diagonal detail']
coeffs2 = pywt.dwt2(original, 'bior1.3')
LL, (LH, HL, HH) = coeffs2
fig = plt.figure(figsize=(12, 3))
for i, a in enumerate([LL, LH, HL, HH]):
    ax = fig.add_subplot(1, 4, i + 1)
    ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray)
    ax.set_title(titles[i], fontsize=10)
    ax.set_xticks([])
    ax.set_yticks([])

fig.tight_layout()
plt.show()


Source Tree


pywt-master/pywt



$ ls -l
total 344
-rw-r--r--@   __init__.py
-rw-r--r--@   _cwt.py
-rw-r--r--@   _doc_utils.py
-rw-r--r--@   _dwt.py
drwxr-xr-x@   _extensions
-rw-r--r--@   _functions.py
-rw-r--r--@   _multidim.py
-rw-r--r--@   _multilevel.py
-rw-r--r--@   _swt.py
-rw-r--r--@   _thresholding.py
-rw-r--r--@   _utils.py
-rw-r--r--@   _wavelet_packets.py
drwxr-xr-x@   data
drwxr-xr-x@   tests


__init__.py



from __future__ import division, print_function, absolute_import
from distutils.version import LooseVersion

from ._extensions._pywt import *
from ._functions import *
from ._multilevel import *
from ._multidim import *
from ._thresholding import *
from ._wavelet_packets import *
from ._dwt import *
from ._swt import *
from ._cwt import *

from . import data

__all__ = [s for s in dir() if not s.startswith('_')]
try:
    # In Python 2.x the name of the tempvar leaks out of the list
    # comprehension.  Delete it to not make it show up in the main namespace.
    del s
except NameError:
    pass

from pywt.version import version as __version__

import numpy as np
if np.lib.NumpyVersion(np.__version__) >= '1.14.0':
    from ._utils import is_nose_running
    if is_nose_running():
        np.set_printoptions(legacy='1.13')

from numpy.testing import Tester
test = Tester().test

pywt-master/pywt/data


__init__.py




from ._readers import ascent, aero, ecg, camera, nino
from ._wavelab_signals import demo_signal


_readers.py


There are 3 test image ndarray stored in files:
  • aero.npz
  • ascent.npz
  • camera.npz



import os

import numpy as np

def camera():
    """
    Get an 8-bit grayscale bit-depth, 512 x 512 derived image for
    easy use in demos

    Parameters
    ----------
    None

    Returns
    -------
    camera : ndarray
    """
    fname = os.path.join(os.path.dirname(__file__), 'camera.npz')
    camera = np.load(fname)['data']
    return camera


  • numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding='ASCII'
  • Load arrays or pickled objects from .npy, .npz or pickled files.
  • numpy.savez_compressed(file, *args, **kwds)
  • Save several arrays into a single file in uncompressed .npz format. If keyword arguments are given, then filenames are taken from the keywords, arrays will be saved in the file with the keyword names. If arguments are passed in with no keywords, then stored file names are arr_0, arr_1, etc.
    
    >>> from tempfile import TemporaryFile
    >>> outfile = TemporaryFile()
    >>> x = np.arange(10)
    >>> y = np.sin(x)
    
    >>> np.savez(outfile, x, y)
    >>> outfile.seek(0) # Only needed here to simulate closing & reopening file
    >>> npzfile = np.load(outfile)
    >>> npzfile.files
    ['arr_1', 'arr_0']
    >>> npzfile['arr_0']
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    

create_dat.py




#!/usr/bin/env python
  
"""Helper script for creating image .dat files by numpy.save

Usage:

    python create_dat.py  

Example (to create aero.dat):

    python create_dat.py aero.png aero.dat

Requires Scipy and PIL.
"""

from __future__ import print_function

import sys

import numpy as np


def main():
    from scipy.misc import imread

    if len(sys.argv) != 3:
        print(__doc__)
        exit()

    image_fname = sys.argv[1]
    dat_fname = sys.argv[2]

    data = imread(image_fname)

    np.savez_compressed(dat_fname, data=data)


if __name__ == "__main__":
    main()

scipy.misc.imread is only available if Python Imaging Library (PIL) is installed.
scipy.misc.imread is deprecated! imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use imageio.imread instead.

_multidim.py

2D and nD Discrete Wavelet Transforms and Inverse Discrete Wavelet Transforms.



def dwt2(data, wavelet, mode='symmetric', axes=(-2, -1)):
    axes = tuple(axes)
    data = np.asarray(data)
    if len(axes) != 2:
        raise ValueError("Expected 2 axes")
    if data.ndim < len(np.unique(axes)):
        raise ValueError("Input array has fewer dimensions than the specified "
                         "axes")

    coefs = dwtn(data, wavelet, mode, axes)
    return coefs['aa'], (coefs['da'], coefs['ad'], coefs['dd'])


  • numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
  • Returns the sorted unique elements of an array.
    
    >>> a = np.array([[1, 1], [2, 3]])
    >>> np.unique(a)
    array([1, 2, 3])
    
    >>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
    >>> np.unique(a, axis=0)
    array([[1, 0, 0], [2, 3, 4]])
    

Examples,


    >>> import numpy as np
    >>> import pywt
    >>> data = np.ones((4,4), dtype=np.float64)
    >>> coeffs = pywt.dwt2(data, 'haar')
    >>> cA, (cH, cV, cD) = coeffs
    >>> cA
    array([[ 2.,  2.],
           [ 2.,  2.]])
    >>> cV
    array([[ 0.,  0.],
           [ 0.,  0.]])



留言

熱門文章