Aggiunte opzioni.

Leonardo Robol [2010-03-03 16:06]
Aggiunte opzioni.
Filename
Filtering/Splitting.py
Filtering/dwt
diff --git a/Filtering/Splitting.py b/Filtering/Splitting.py
deleted file mode 100755
index 80168a8..0000000
--- a/Filtering/Splitting.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-
-import Filtering, pylab, sys
-from numpy import array, sqrt, memmap, roll
-from numpy.linalg import norm
-
-def Output (string):
-    """Output with colors :)"""
-    print " \033[1m=>\033[0m\033[32;1m %s \033[0m" % string
-
-
-class SplittingExample():
-
-    def __init__(self):
-
-        # Scelgo la filterbank da utilizzare
-        # filterBank = Filtering.HaarFilterBank
-        # filterBank = Filtering.DaubechiesFilterBank
-        filterBank = Filtering.StrangFilterBank
-        filterBank.SetDepth(8)
-
-        samples = self.LoadSamples ("sunny.pcm")
-        wavelets = filterBank.Split (samples)
-
-        # Mostro la decomposizione se l'utente l'ha chiesto
-	if len(sys.argv) > 1 and sys.argv[1] == "show":
-            self.Show (wavelets)
-
-
-        if len(sys.argv) > 1 and sys.argv[1] == "rebuild":
-            rebuilt = filterBank.Rebuild (wavelets)
-            Output ("||rebuilt - samples|| = %f" % norm(rebuilt - samples[0:len(rebuilt)]))
-            self.WriteSamples(rebuilt, "rebuilt.pcm")
-
-
-    def LoadSamples(self, filename = "sunny.pcm"):
-        """
-        Load the samples from an audio file
-        """
-        Output("Loading samples from %s" % filename)
-        samples = memmap (filename,
-                          dtype="<h",
-                          mode="r")
-        return samples
-
-    def WriteSamples(self, samples, filename):
-        Output("Writing samples to %s" % filename)
-        data = memmap (filename,
-                       dtype="<h",
-                       mode="w+",
-                       shape = len(samples))
-        data[:] = samples[:]
-        data.flush ()
-
-    def Show(self, wavelets):
-        """
-        Shows the result of filtering
-        """
-        scale = 1
-        offset = -90000
-        for samples in wavelets[0:-1]:
-            pylab.plot (range(0, scale * len(samples), scale), samples + offset)
-            offset += 30000
-            scale = 2*scale
-        pylab.plot (range(0, int(0.5*scale*len(wavelets[-1])), int(0.5 * scale)), wavelets[-1] + offset)
-        pylab.show ()
-
-
-if __name__ == "__main__":
-
-    SplittingExample ()
diff --git a/Filtering/dwt b/Filtering/dwt
new file mode 100755
index 0000000..ee2cc7b
--- /dev/null
+++ b/Filtering/dwt
@@ -0,0 +1,118 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+
+import Filtering, pylab
+from numpy import array, sqrt, memmap, roll
+from numpy.linalg import norm
+
+from optparse import OptionParser
+
+def Output (string):
+    """Output with colors :)"""
+    print " \033[1m=>\033[0m\033[32;1m %s \033[0m" % string
+
+
+class DWT():
+
+    def __init__(self, filename, action = 'show', filewrite = 'rebuilt.pcm',
+                 filterbank = 'haar', depth = 4):
+
+        # Scelgo la filterbank da utilizzare
+        if filterbank == 'haar':
+            filterBank = Filtering.HaarFilterBank
+        elif (filterbank == 'daubechies') or (filterbank.lower() == 'd4'):
+            filterBank = Filtering.DaubechiesFilterBank
+        elif filterbank == 'strang':
+            filterBank = Filtering.StrangFilterBank
+        else:
+            filterBank = Filtering.HaarFilterBank
+            Output ("FilterBank %s not known. Setting 'haar'" % filterbank)
+
+        filterBank.SetDepth (int(depth))
+
+        samples = self.LoadSamples (filename)
+        wavelets = filterBank.Split (samples)
+
+        # Mostro la decomposizione se l'utente l'ha chiesto
+        if action == 'show':
+            self.Show (wavelets)
+
+
+        if action is 'rebuild':
+            rebuilt = filterBank.Rebuild (wavelets)
+            Output ("||rebuilt - samples|| = %f" % norm(rebuilt - samples[0:len(rebuilt)]))
+            self.WriteSamples(rebuilt, filewrite)
+
+
+    def LoadSamples(self, filename = "sunny.pcm"):
+        """
+        Load the samples from an audio file
+        """
+        Output("Loading samples from %s" % filename)
+        samples = memmap (filename,
+                          dtype="<h",
+                          mode="r")
+        return samples
+
+    def WriteSamples(self, samples, filename):
+        Output("Writing samples to %s" % filename)
+        data = memmap (filename,
+                       dtype="<h",
+                       mode="w+",
+                       shape = len(samples))
+        data[:] = samples[:]
+        data.flush ()
+
+    def Show(self, wavelets):
+        """
+        Shows the result of filtering
+        """
+        scale = 1
+        offset = -90000
+        for samples in wavelets[0:-1]:
+            pylab.plot (range(0, scale * len(samples), scale), samples + offset)
+            offset += 30000
+            scale = 2*scale
+        pylab.plot (range(0, int(0.5*scale*len(wavelets[-1])), int(0.5 * scale)), wavelets[-1] + offset)
+        pylab.show ()
+
+
+if __name__ == "__main__":
+
+    parser = OptionParser ()
+    parser.add_option("-f", "--file", dest="filename",default=None,
+                      help="Read samples from this .pcm file")
+    parser.add_option("-r", "--rebuild", dest="rebuild",
+                      default=False, action="store_true",
+                      help="Make DWT and then IDWT")
+    parser.add_option("-w", "--write", dest="filewrite", default='rebuilt.pcm',
+                      help="Write reconstructed samples to this file")
+    parser.add_option("-s", "--show", dest="show",
+                      default=True, action="store_true",
+                      help="Show the decomposed waves (this is the default)")
+    parser.add_option("-d", "--depth", dest="depth",
+                      default=4, help="Set the recursion level of the filter bank (default is 4)")
+    parser.add_option("-b", "--filterbank", dest="filterbank", default='haar',
+                      help="Set the filterbank to use in the transform. Valid inputs are 'haar', 'daubechies', 'D4', 'strang'")
+
+
+    (options, args) = parser.parse_args ()
+
+    if options.filename is None:
+        parser.error ("Please a specify a pcm file to read the samples from")
+
+
+    if options.rebuild:
+        DWT(filename = options.filename, action = 'rebuild',
+            filewrite = options.filewrite, depth = options.depth,
+            filterbank = options.filterbank)
+
+    elif options.show:
+        DWT(filename = options.filename, action = 'show',
+            depth = options.depth, filterbank = options.filterbank)
+
+
+
+
+
ViewGit