Showing posts with label scipy. Show all posts
Showing posts with label scipy. Show all posts

Tuesday, January 23, 2018

How to efficiently pass function through?

Leave a Comment

Motivation

Take a look at the following picture.

enter image description here

Given are the red, blue, and green curve. I would like to find at each point on the x axis the dominating curve. This is shown as the black graph in the picture. From the properties of the red, green, and blue curve (increasing and constant after a while) this boils down to find the dominating curve on the very right hand side and then move towards the left hand side finding all intersection points and update the dominating curve.

This outlined problem should be solved T times. There is one final twist in the problem. The blue, green, and red curve of the next iteration are constructed via the dominating solution from the previous iteration plus some varying parameters. As an example in the picture above: The solution is the black function. This function is used to generate a new blue, green, and red curve. Then the problem start again to find the dominating one for these new curves etc.

Question in a nutshell
In each iteration I start at the fixed very right hand side and evaluate all three functions to see which is the dominating one. This evaluations are taking longer and longer over iteration. My feeling is that I don't pass optimally the old dominating function to construct the new blue, green, and red curve. Reason: I got in an earlier version a maximum recursion depth error. Other parts of the code where the value of the current dominating function (which is essential either the green, red, or blue curve) is required are also taking longer and longer with iteration.

For 5 iterations just evaluating the functions on one point on the very right hand side grows:

The results were produced via

test = A(5, 120000, 100000)  

And then running

test.find_all_intersections()  >>> test.find_all_intersections() iteration 4 to compute function values it took 0.0102479457855 iteration 3 to compute function values it took 0.0134601593018 iteration 2 to compute function values it took 0.0294270515442 iteration 1 to compute function values it took 0.109843969345 iteration 0 to compute function values it took 0.823768854141 

I would like to know why is this the case and if one can program it more efficiently.

Detailed Code explanation

I quickly summarize the most important functions. The complete code can be found further below. If there are any other questions regarding the code I'm more than happy to elaborate / clarify.

  1. Method u: For the recurring task of generating a new batch of the green, red, and blue curve above we need the old dominating one. u is the initialization to be used in the very first iteration.

  2. Method _function_template: The function generates versions of the green, blue, and red curve by using different parameters. It returns a function of a single input.

  3. Method eval: This is the core function to generate the blue, green, and red versions every time. It takes three varying parameters each iteration: vfunction which is the dominating function from the previous step, m, and s which are two parameters (flaots) affecting the shape of the resulting curve. The other parameters are the same in each iteration. In the code there are sample values for m and s for each iteration. For the more geeky ones: It's to approximate an integral where m and s are the expected mean and standard deviation of the underlying normal distribution. The approximation is done via Gauss-Hermite nodes / weights.

  4. Method find_all_intersections: This is the core method finding in each iteration the dominating one. It constructs a dominating function via a piece wise concatenation of the blue, green, and red curve. This is achieved via the function piecewise.

Here is the complete code

import numpy as np import pandas as pd from scipy.optimize import brentq import multiprocessing as mp import pathos as pt import timeit import math class A(object):     def u(self, w):         _w = np.asarray(w).copy()         _w[_w >= 120000] = 120000         _p = np.maximum(0, 100000 - _w)         return _w - 1000*_p**2      def __init__(self, T, upper_bound, lower_bound):         self.T = T         self.upper_bound = upper_bound         self.lower_bound = lower_bound      def _function_template(self, *args):         def _f(x):             return self.evalv(x, *args)         return _f      def evalv(self, w, c, vfunction, g, m, s, gauss_weights, gauss_nodes):         _A = np.tile(1 + m + math.sqrt(2) * s * gauss_nodes, (np.size(w), 1))         _W = (_A.T * w).T         _W = gauss_weights * vfunction(np.ravel(_W)).reshape(np.size(w),                                                              len(gauss_nodes))         evalue = g*1/math.sqrt(math.pi)*np.sum(_W, axis=1)         return c + evalue      def find_all_intersections(self):          # the hermite gauss weights and nodes for integration         # and additional paramters used for function generation          gauss = np.polynomial.hermite.hermgauss(10)         gauss_nodes = gauss[0]         gauss_weights = gauss[1]         r = np.asarray([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,                         1., 1., 1., 1., 1., 1., 1., 1., 1.])         m = [[0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.03836174909668277, 0.08543620707856969, 0.15548297423808233],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.03836174909668277, 0.08543620707856969, 0.15548297423808233],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.03836174909668277, 0.08543620707856969, 0.15548297423808233],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038063407778193614, 0.08475713587463352, 0.15420895520972322],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.03836174909668277, 0.08543620707856969, 0.15548297423808233],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624],              [0.038212567720998125, 0.08509661835487026, 0.15484578903763624]]          s = [[0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019529101011406914, 0.04708607140891122, 0.20089341636351565],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.019529101011406914, 0.04708607140891122, 0.20089341636351565],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019529101011406914, 0.04708607140891122, 0.20089341636351565],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.01945441966324046, 0.04690600929081242, 0.200125178687699],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019529101011406914, 0.04708607140891122, 0.20089341636351565],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142],              [0.019491796104351332, 0.04699612658674578, 0.20050966545654142]]          self.solution = []          n_cpu = mp.cpu_count()         pool = pt.multiprocessing.ProcessPool(n_cpu)          # this function is used for multiprocessing         def call_f(f, x):             return f(x)          # this function takes differences for getting cross points         def _diff(f_dom, f_other):             def h(x):                 return f_dom(x) - f_other(x)             return h          # finds the root of two function         def find_roots(F, u_bound, l_bound):                 try:                     sol = brentq(F, a=l_bound,                                  b=u_bound)                     if np.absolute(sol - u_bound) > 1:                         return sol                     else:                         return l_bound                 except ValueError:                     return l_bound          # piecewise function         def piecewise(l_comp, l_f):             def f(x):                 _ind_f = np.digitize(x, l_comp) - 1                 if np.isscalar(x):                     return l_f[_ind_f](x)                 else:                     return np.asarray([l_f[_ind_f[i]](x[i])                                        for i in range(0, len(x))]).ravel()             return f          _u = self.u          for t in range(self.T-1, -1, -1):             print('iteration' + ' ' + str(t))              l_bound, u_bound = 0.5*self.lower_bound, self.upper_bound             l_ordered_functions = []             l_roots = []             l_solution = []              # build all function variations              l_functions = [self._function_template(0, _u, r[t], m[t][i], s[t][i],                                                    gauss_weights, gauss_nodes)                            for i in range(0, len(m[t]))]              # get the best solution for the upper bound on the very             # right hand side of wealth interval              array_functions = np.asarray(l_functions)             start_time = timeit.default_timer()             functions_values = pool.map(call_f, array_functions.tolist(),                                         len(m[t]) * [u_bound])             elapsed = timeit.default_timer() - start_time             print('to compute function values it took')             print(elapsed)              ind = np.argmax(functions_values)             cross_points = len(m[t]) * [u_bound]             l_roots.insert(0, u_bound)             max_m = m[t][ind]             l_solution.insert(0, max_m)              # move from the upper bound twoards the lower bound             # and find the dominating solution by exploring all cross             # points.              test = True              while test:                 l_ordered_functions.insert(0, array_functions[ind])                 current_max = l_ordered_functions[0]                  l_c_max = len(m[t]) * [current_max]                 l_u_cross = len(m[t]) * [cross_points[ind]]                  # Find new cross points on the smaller interval                  diff = pool.map(_diff, l_c_max, array_functions.tolist())                 cross_points = pool.map(find_roots, diff,                                         l_u_cross, len(m[t]) * [l_bound])                  # update the solution, cross points and current                 # dominating function.                  ind = np.argmax(cross_points)                 l_roots.insert(0, cross_points[ind])                 max_m = m[t][ind]                 l_solution.insert(0, max_m)                  if cross_points[ind] <= l_bound:                     test = False              l_ordered_functions.insert(0, l_functions[0])             l_roots.insert(0, 0)             l_roots[-1] = np.inf              l_comp = l_roots[:]             l_f = l_ordered_functions[:]              # build piecewise function which is used for next             # iteration.              _u = piecewise(l_comp, l_f)             _sol = pd.DataFrame(data=l_solution,                                 index=np.asarray(l_roots)[0:-1])             self.solution.insert(0, _sol)         return self.solution 

2 Answers

Answers 1

Let's start by changing the code to output the current iteration:

_u = self.u for t in range(0, self.T):     print(t)     lparams = np.random.randint(self.a, self.b, 6).reshape(3, 2).tolist()     functions = [self._function_template(_u, *lparams[i])                  for i in range(0, 3)]     # evaluate functions     pairs = list(itertools.combinations(functions, 2))     fval = [F(diff(*pairs[i]), self.a, self.b) for i in range(0, 3)]     ind = np.sort(np.unique(np.random.randint(self.a, self.b, 10)))     _u = _temp(ind, np.asarray(functions)[ind % 3]) 

Looking into the line causing the behaviour,

fval = [F(diff(*pairs[i]), self.a, self.b) for i in range(0, 3)] 

functions of interest would be F and diff. The latter being straightforward, the former:

def F(f, a, b):     try:         brentq(f, a=a, b=b)     except ValueError:         pass 

Hmm, swallowing exceptions, let's see what happens if we:

def F(f, a, b):     brentq(f, a=a, b=b) 

Immediately, for the first function and on the first iteration, an error is thrown:

ValueError: f(a) and f(b) must have different signs

Looking at the docs this is a prerequisite of the root finding function brentq. Let's change the definition once more to monitor this condition on each iteration.

def F(f, a, b):     try:         brentq(f, a=a, b=b)     except ValueError as e:         print(e) 

The output is

i f(a) and f(b) must have different signs f(a) and f(b) must have different signs f(a) and f(b) must have different signs 

for i ranging from 0 to 57. Meaning, the first time the function F ever does any real work is for i=58. And it keeps doing so for higher values of i.

Conclusion: it takes longer for these higher values, because:

  1. the root is never calculated for the lower values
  2. the number of calculations grows linear for i>58

Answers 2

Your code is really far too complex to explain your problem - strive for something simpler. Sometimes you have to write code just to demonstrate the problem.

I'm taking a stab, based purely on your description rather than your code (although I ran the code and verified) . Here's your problem:

method eval: This is the core function to generate the blue, green and red versions every time. It takes three varying parameters each iteration: vfunction which is the dominating function from the previous step, m and s which are two parameters (flaots) affecting the shape of the resulting curve.

Your vfunction parameter is more complex on each iteration. You are passing a nested function built up over previous iterations, which causes a recursive execution. Each iteration increases the depth of the recursive call.

How can you avoid this? There's no easy or built in way. The simplest answer is - assuming the inputs to these functions are consistent - to store the functional result (i.e. the numbers) rather than the function themselves. You can do this as long as you have a finite number of known inputs.

If the inputs to the underlying functions aren't consistent then there's no shortcut. You need to repeatedly evaluate those underlying functions. I see that you're doing some piecewise splicing of the underlying functions - you can test whether the cost of doing so exceeds the cost of simply taking the max of each of the underlying functions.

The test that I ran (10 iterations) took a few seconds. I don't see that as a problem.

Read More

Wednesday, July 19, 2017

How to perform cluster with weights/density in python? Something like kmeans with weights?

Leave a Comment

My data is like this:

powerplantname, latitude, longitude, powergenerated A, -92.3232, 100.99, 50 B, <lat>, <long>, 10 C, <lat>, <long>, 20 D, <lat>, <long>, 40 E, <lat>, <long>, 5 

I want to be able to cluster the data into N number of clusters (say 3). Normally I would use a kmeans:

import numpy as np  import matplotlib.pyplot as plt from scipy.cluster.vq import kmeans2, whiten coordinates= np.array([            [lat, long],            [lat, long],             ...            [lat, long]            ]) x, y = kmeans2(whiten(coordinates), 3, iter = 20)   plt.scatter(coordinates[:,0], coordinates[:,1], c=y); plt.show() 

The problem with this is it does not account for any weighting (in this case, my powergenerated value) I want to ideally have my clusters taking the value "powergenerated" into account, trying to keep the clusters not only spatially close, but also have close to relatively equal total powergenerated.

Should I be doing this with kmeans (or some other method)? Or is there something else I should be using for this problem that would be better?

1 Answers

Answers 1

Or is there something else I should be using for this problem that would be better?

In order to take into account simultaneously the geographical distance among centrals and the generated power you should define a proper metric. The function below computes the distance between two points on Earth's surface from their latitudes and longitudes through the haversine formula and adds the absolute value of the generated power difference multiplied by a weighting factor. The value of the weight determines the relative influence of distance and power difference in the clustering process.

import numpy as np  def custom_metric(central_1, central_2, weight=1):     lat1, lng1, pow1 = central_1     lat2, lng2, pow2 = central_2      lat1, lat2, lng1, lng2 = np.deg2rad(np.asarray([lat1, lat2, lng1, lng2]))      dlat = lat2 - lat1     dlng = lng2 - lng1      h = (1 - np.cos(dlat))/2. + np.cos(lat1)*np.cos(lat2)*(1 - np.cos(dlng))/2.     km = 2*6371*np.arcsin(np.sqrt(h))      MW = np.abs(pow2 - pow1)      return km + weight*MW 

Should I be doing this with kmeans (or some other method)?

Unfortunately the current implementations of SciPy's kmeans2 and scikit-learn's KMeans only support Euclidean distance. An alternative method would consist in performing hierarchical clustering through the SciPy's clustering package to group the centrals according to the metric just defined.

Demo

Let us first generate mock data, namely feature vectors for 8 centrals with random values:

N = 8 np.random.seed(0) lat = np.random.uniform(low=-90, high=90, size=N) lng = np.random.uniform(low=-180, high=180, size=N) power = np.random.randint(low=5, high=50, size=N) data = np.vstack([lat, lng, power]).T 

The content of variable data yielded by the snippet above looks like this:

array([[   8.7864,  166.9186,   21.    ],        [  38.7341,  -41.9611,   10.    ],        [  18.4974,  105.021 ,   20.    ],        [   8.079 ,   10.4022,    5.    ],        [ -13.7421,   24.496 ,   23.    ],        [  26.2609,  153.2148,   40.    ],        [ -11.2343, -154.427 ,   29.    ],        [  70.5191, -148.6335,   34.    ]]) 

To divide those data into three different groups we have to pass data and custom_metric to the linkage function (check the docs to find out more on parameter method), and then pass the returned linkage matrix to the cut_tree function with n_clusters=3.

from scipy.cluster.hierarchy import linkage, cut_tree Z = linkage(data, method='average', metric=custom_metric) y = cut_tree(Z, 3).flatten() 

As a result we get the group membership (array y) for each central:

array([0, 1, 0, 2, 2, 0, 0, 1]) 

The results above depend on the value of weight. If you wish to use a value different to 1 (for example 250) you can change the default value like this:

def custom_metric(central_1, central_2, weight=250): 

Alternatively, you could set the parameter metric in the call to linkage to a lambda expression as follows: metric=lambda x, y: custom_metric(x, y, 250).

Finally, to gain a deeper insight into the hierarchical/agglomerative clustering you could plot it as a dendrogram:

from scipy.cluster.hierarchy import dendrogram dendrogram(Z) 

dendrogram

Read More

Friday, April 21, 2017

Producing spectrogram from microphone

Leave a Comment

Below I have code that will take input from a microphone, and if the average of the audio block passes a certain threshold it will produce a spectrogram of the audio block (which is 30 ms long). Here is what a generated spectrogram looks like in the middle of normal conversation:

enter image description here

From what I have seen, this doesn't look anything like what I'd expect a spectrogram to look like given the audio and it's environment. I was expecting something more like the following (transposed to preserve space):

enter image description here

The microphone I'm recording with is the default on my Macbook, any suggestions on what's going wrong?


record.py:

import pyaudio import struct import math import numpy as np from scipy import signal import matplotlib.pyplot as plt   THRESHOLD = 40 # dB RATE = 44100 INPUT_BLOCK_TIME = 0.03 # 30 ms INPUT_FRAMES_PER_BLOCK = int(RATE * INPUT_BLOCK_TIME)  def get_rms(block):     return np.sqrt(np.mean(np.square(block)))  class AudioHandler(object):     def __init__(self):         self.pa = pyaudio.PyAudio()         self.stream = self.open_mic_stream()         self.threshold = THRESHOLD         self.plot_counter = 0      def stop(self):         self.stream.close()      def find_input_device(self):         device_index = None         for i in range( self.pa.get_device_count() ):             devinfo = self.pa.get_device_info_by_index(i)             print('Device %{}: %{}'.format(i, devinfo['name']))              for keyword in ['mic','input']:                 if keyword in devinfo['name'].lower():                     print('Found an input: device {} - {}'.format(i, devinfo['name']))                     device_index = i                     return device_index          if device_index == None:             print('No preferred input found; using default input device.')          return device_index      def open_mic_stream( self ):         device_index = self.find_input_device()          stream = self.pa.open(  format = pyaudio.paInt16,                                 channels = 1,                                 rate = RATE,                                 input = True,                                 input_device_index = device_index,                                 frames_per_buffer = INPUT_FRAMES_PER_BLOCK)          return stream      def processBlock(self, snd_block):         f, t, Sxx = signal.spectrogram(snd_block, RATE)         plt.pcolormesh(t, f, Sxx)         plt.ylabel('Frequency [Hz]')         plt.xlabel('Time [sec]')         plt.savefig('data/spec{}.png'.format(self.plot_counter), bbox_inches='tight')         self.plot_counter += 1      def listen(self):         try:             raw_block = self.stream.read(INPUT_FRAMES_PER_BLOCK, exception_on_overflow = False)             count = len(raw_block) / 2             format = '%dh' % (count)             snd_block = np.array(struct.unpack(format, raw_block))         except Exception as e:             print('Error recording: {}'.format(e))             return          amplitude = get_rms(snd_block)         if amplitude > self.threshold:             self.processBlock(snd_block)         else:             pass  if __name__ == '__main__':     audio = AudioHandler()     for i in range(0,100):         audio.listen() 

Edits based on comments:

If we constrain the rate to 16000 Hz and use a logarithmic scale for the colormap, this is an output for tapping near the microphone:

enter image description here

Which still looks slightly odd to me, but also seems like a step in the right direction.

Using Sox and comparing with a spectrogram generated from my program:

4 Answers

Answers 1

First, observe that your code plots up to 100 spectrograms (if processBlock is called multiple times) on top of each other and you only see the last one. You may want to fix that. Furthermore, I assume you know why you want to work with 30ms audio recordings. Personally, I can't think of a practical application where 30ms recorded by a laptop microphone could give interesting insights. It hinges on what you are recording and how you trigger the recording, but this issue is tangential to the actual question.

Otherwise the code works perfectly. With just a few small changes in the processBlock function, applying some background knowledge, you can get informative and aesthetic spectrograms.

So let's talk about actual spectrograms. I'll take the SoX output as reference. The colorbar annotation says that it is dBFS. I don't know what FS stands for but dB means Decibel, which is a logarithmic scale. So, let's first convert the spectrogram to dB:

    f, t, Sxx = signal.spectrogram(snd_block, RATE, nperseg=64)        dBS = 10 * np.log10(Sxx)  # convert to dB     plt.pcolormesh(t, f, dBS) 

enter image description here

This improved the color scale. Now we see noise in the higher frequency bands that was hidden before. Next, let's tackle time resolution. The spectrogram divides the signal into segments (default length is 256) and computes the spectrum for each. This means we have excellent frequency resolution but very poor time resolution because only a few such segments fit into the signal window (which is about 1300 samples long). There is always a trade-off between time and frequency resolution. This is related to the uncertainty principle. So let's trade some frequency resolution for time resolution by splitting the signal into shorter segments:

f, t, Sxx = signal.spectrogram(snd_block, RATE, nperseg=64) 

enter image description here

Great! Now we got a relatively balanced resolution on both axes - but wait! Why is the result so pixelated?! Actually, this is all the information there is in the short 30ms time window. There are only so many ways 1300 samples can be distributed in two dimensions. However, we can cheat a bit and use higher FFT resulution and overlapping segments. This makes the result smoother although it does not provide additional information:

f, t, Sxx = signal.spectrogram(snd_block, RATE, nperseg=64, nfft=256, noverlap=60) 

enter image description here

Behold pretty spectral interference patterns. (These patterns depend on the window function used, but's let not get caught in details, here. See the window argument of the spectrogram function to play with these.) The result looks nice, but actually does not contain any more information than the previous image.

To make the result more SoX-lixe observe that the SoX spectrogram is rather smeared on the time axis. You get this effect by using the original low time resolution (long segments) but let them overlap for smoothness:

f, t, Sxx = signal.spectrogram(snd_block, RATE, noverlap=250) 

enter image description here

I personally prefer the 3rd solution, but you will need to find your own preferred time/frequency trade-off.

Finally, let's use a colormap that is more like SoX's:

plt.pcolormesh(t, f, dBS, cmap='inferno') 

enter image description here

A short comment on the following line:

THRESHOLD = 40 # dB 

The threshold is compared against the RMS of the input signal, which is not measured in dB but raw amplitude units.

Answers 2

UPDATE to make my answer clearer and hopefully compliment the excellent explanation by @kazemakase, I found three things that I hope will help:

  1. Use LogNorm:

    plt.pcolormesh(t, f, Sxx, cmap='RdBu', norm=LogNorm(vmin=Sxx.min(), vmax=Sxx.max())) 
  2. use numpy's fromstring method

Turns out the RMS calculation wont work with this method as the data is constrained length data type and overflows become negative: ie 507*507=-5095.

  1. use colorbar() as eveything becomes easier when you can see scale

    plt.colorbar() 

Original Answer:

I got a decent result playing a 10kHz frequency into your code with only a couple of alterations:

  • import the LogNorm

    from matplotlib.colors import LogNorm 
  • Use the LogNorm in the mesh

    plt.pcolormesh(t, f, Sxx, cmap='RdBu', norm=LogNorm(vmin=Sxx.min(), vmax=Sxx.max())) 

This gave me: LogNorm Scale pcolormesh

You may also need to call plt.close() after the savefig, and I think the stream read needs some work as later images were dropping the first quarter of the sound.

Id also recommend plt.colorbar() so you can see the scale it ends up using

UPDATE: seeing as someone took the time to downvote

Heres my code for a working version of the spectrogram. It captures five seconds of audio and writes them out to a spec file and an audio file so you can compare. Theres stilla lot to improve and its hardly optimized: Im sure its dropping chunks because of the time to write audio and spec files. A better approach would be to use the non-blocking callback and I might do this later

The major difference to the original code was the change to get the data in the right format for numpy:

np.fromstring(raw_block,dtype=np.int16) 

instead of

struct.unpack(format, raw_block) 

This became obvious as a major problem as soon as I tried to write the audio to a file using:

scipy.io.wavfile.write('data/audio{}.wav'.format(self.plot_counter),RATE,snd_block) 

Heres a nice bit of music, drums are obvious:

some music

The code:

import pyaudio import struct import math import numpy as np from scipy import signal import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import time from scipy.io.wavfile import write  THRESHOLD = 0 # dB RATE = 44100 INPUT_BLOCK_TIME = 1 # 30 ms INPUT_FRAMES_PER_BLOCK = int(RATE * INPUT_BLOCK_TIME) INPUT_FRAMES_PER_BLOCK_BUFFER = int(RATE * INPUT_BLOCK_TIME)  def get_rms(block):     return np.sqrt(np.mean(np.square(block)))  class AudioHandler(object):     def __init__(self):         self.pa = pyaudio.PyAudio()         self.stream = self.open_mic_stream()         self.threshold = THRESHOLD         self.plot_counter = 0      def stop(self):         self.stream.close()      def find_input_device(self):         device_index = None         for i in range( self.pa.get_device_count() ):             devinfo = self.pa.get_device_info_by_index(i)             print('Device %{}: %{}'.format(i, devinfo['name']))              for keyword in ['mic','input']:                 if keyword in devinfo['name'].lower():                     print('Found an input: device {} - {}'.format(i, devinfo['name']))                     device_index = i                     return device_index          if device_index == None:             print('No preferred input found; using default input device.')          return device_index      def open_mic_stream( self ):         device_index = self.find_input_device()          stream = self.pa.open(  format = self.pa.get_format_from_width(2,False),                                 channels = 1,                                 rate = RATE,                                 input = True,                                 input_device_index = device_index)          stream.start_stream()         return stream      def processBlock(self, snd_block):         f, t, Sxx = signal.spectrogram(snd_block, RATE)         zmin = Sxx.min()         zmax = Sxx.max()         plt.pcolormesh(t, f, Sxx, cmap='RdBu', norm=LogNorm(vmin=zmin, vmax=zmax))         plt.ylabel('Frequency [Hz]')         plt.xlabel('Time [sec]')         plt.axis([t.min(), t.max(), f.min(), f.max()])         plt.colorbar()         plt.savefig('data/spec{}.png'.format(self.plot_counter), bbox_inches='tight')         plt.close()         write('data/audio{}.wav'.format(self.plot_counter),RATE,snd_block)         self.plot_counter += 1      def listen(self):         try:             print "start", self.stream.is_active(), self.stream.is_stopped()             #raw_block = self.stream.read(INPUT_FRAMES_PER_BLOCK, exception_on_overflow = False)              total = 0             t_snd_block = []             while total < INPUT_FRAMES_PER_BLOCK:                 while self.stream.get_read_available() <= 0:                   print 'waiting'                   time.sleep(0.01)                 while self.stream.get_read_available() > 0 and total < INPUT_FRAMES_PER_BLOCK:                     raw_block = self.stream.read(self.stream.get_read_available(), exception_on_overflow = False)                     count = len(raw_block) / 2                     total = total + count                     print "done", total,count                     format = '%dh' % (count)                     t_snd_block.append(np.fromstring(raw_block,dtype=np.int16))             snd_block = np.hstack(t_snd_block)         except Exception as e:             print('Error recording: {}'.format(e))             return          self.processBlock(snd_block)  if __name__ == '__main__':     audio = AudioHandler()     for i in range(0,5):         audio.listen() 

Answers 3

I think the problem is that you are trying to do the spectrogram of a 30ms audio block, which is so short that you can consider the signal as stationary.
The spectrogram is in fact the STFT, and you can find this also in the Scipy documentation:

scipy.signal.spectrogram(x, fs=1.0, window=('tukey', 0.25), nperseg=None, noverlap=None, nfft=None, detrend='constant', return_onesided=True, scaling='density', axis=-1, mode='psd')

Compute a spectrogram with consecutive Fourier transforms.

Spectrograms can be used as a way of visualizing the change of a nonstationary signal’s frequency content over time.

In the first figure you have four slices which are the result of four consecutive fft on your signal block, with some windowing and overlapping. The second figure has a unique slice, but it depends on the spectrogram parameters you have used.
The point is what do you want to do with that signal. What is the purpose of the algorithm?

Answers 4

I am not sure that working directly in Python is the best way for sound processing and most precisely with FFT... [ in my opinion using cython appear like an obligation in sound processing with python]

Have you evaluate the possiblity to bind any external FFT method (using fftw for example) and keep using python only to dispatch job to external method & to update the picture result ?

You may found some information relatively to optimze FFT in python here, and may also take a look at scipy FFT implementation.

Read More

Sunday, May 1, 2016

How to remove an extension to a blob caused by morphology

Leave a Comment

I have an image that I'm eroding and dilating like so:

kernel = np.ones((5,5),np.float32)/1         eroded_img = cv2.erode(self.inpainted_adjusted_image, kernel, iterations=10)         dilated_img = cv2.dilate(eroded_img, kernel, iterations=10) 

Here's the result of the erosion and dilation:

enter image description here

and then I'm taking a threshold of it like so:

self.thresh = cv2.threshold(dilated_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] 

But the threshold gives me an unwanted extension that I've marked in the image below (The region above the red line is the unwanted region):

enter image description here

How do I get rid of this unwanted region? Is there a better way to do what I'm doing?

3 Answers

Answers 1

Working with a different type of threshold (adaptive threshold, which takes local brigthness into account) will already get rid of your problem: The adaptive threshold result is what you are looking for.

enter image description here

[EDIT: I have taken the liberty of adding some code on Hough circles. I admit that I have played with the parameters for this single image to get a nice looking result, though I do not know what type of accuracy you are needing for such a type of problem]

import cv2 import numpy as np import matplotlib.pyplot as plt  img = cv2.imread('image.png',0) thresh = cv2.threshold(img, 210, 255, cv2.ADAPTIVE_THRESH_MEAN_C)[1] canny = cv2.Canny(thresh,50,150) cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)  circles = cv2.HoughCircles(canny,cv2.HOUGH_GRADIENT,1,20, param1=50,param2=23,minRadius=0,maxRadius=0) circles = np.uint16(np.around(circles))   for i in circles[0,:]:     # draw the outer circle     cv2.circle(cimg,(i[0],i[1]),i[2],(255,0,0),3)     # draw the center of the circle     cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)  titles = ['Original Image', 'Adaptive Thresholding', "Canny", "Hough Circle"] images = [img, thresh, canny, cimg] for i in xrange(4):     plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')     plt.title(titles[i])     plt.xticks([]),plt.yticks([]) plt.show() 

Let us know if this is not yet sufficient.

Answers 2

From the binary Image it would be fairly easy to fit a circle using a Hough transform. Once you have the outer boundary of the circle i would suggest bleeding the boundary and cropping out the portion that outside the boundary.

Another approach is to adjust your threshold value. It looks like you could get away with that. You might need some morphological operations to get a clean edge. Using a disk kernel will help retain the shape to a good extent.

Answers 3

Since your question has been rolled back to its original version, I have attached a solution using flood fill which works on your images.

import numpy as np import cv2 import sys import matplotlib.pyplot as plt  img = cv2.imread('image.png', 0)  h, w = img.shape[:2] mask = np.zeros((h+2, w+2), np.uint8)  gray = cv2.blur(img,(5,5)) (minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(gray) print maxLoc  fixed_range = True connectivity = 4  flooded = img.copy() mask[:] = 0 connectivity = 4 #8 flags = connectivity  flags |= cv2.FLOODFILL_FIXED_RANGE cv2.floodFill(flooded, mask, maxLoc, (255, 255, 255), (60,)*3, (60,)*3, flags)  thresh = cv2.threshold(flooded, 250, 255, cv2.THRESH_BINARY)[1]  titles = ['Original Image', 'Blurred', "Floodfill", "Threshold"] images = [img, gray, flooded, thresh] for i in xrange(4):     plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')     plt.title(titles[i])     plt.xticks([]),plt.yticks([]) plt.show() 

enter image description here

Read More