Convolution and Deconvolution in Python using scipy.signal

拟墨画扇 提交于 2019-12-30 11:19:28

问题


I am trying to do some (de)convolution with audio samples. I have one sample s and the same sample with some filters added on top of it s_f. Both samples are represented as numpy arrays. I want to deconvolve them in order to get an array that represents the isolated filter f. Once I do that I should be able to reproduce s_f using convolution of s and f.

Here's the code:

f = signal.deconvolve(s, s_f)
convolved = signal.convolve(s, f)

However, I get the following error on the second line:

ValueError: in1 and in2 should have the same rank

Does anyone know what am I doing wrong here?

Thanks much, omer


回答1:


deconvolve returns two arrays, the quotient and the remainder. So try:

f, r = signal.deconvolve(s, s_f)

For a long time, deconvolve has not had a proper docstring, but it has one in the master branch on github: https://github.com/scipy/scipy/blob/master/scipy/signal/signaltools.py#L731

The docstring shows an example of the use of deconvolve. Here's another (sig is scipy.signal and np is numpy):

The signal to be deconvolved is z, and the filter coefficients are in filter:

In [9]: z
Out[9]: 
array([  0.5,   2.5,   6. ,   9.5,  11. ,  10. ,   9.5,  11.5,  10.5,
         5.5,   2.5,   1. ])

In [10]: filter = np.array([0.5, 1.0, 0.5])

Apply deconvolve:

In [11]: q, r = sig.deconvolve(z, filter)

In [12]: q
Out[12]: array([ 1.,  3.,  5.,  6.,  5.,  4.,  6.,  7.,  1.,  2.])

Apply the filter to q to verify that we get back z:

In [13]: sig.convolve(q, filter)
Out[13]: 
array([  0.5,   2.5,   6. ,   9.5,  11. ,  10. ,   9.5,  11.5,  10.5,
         5.5,   2.5,   1. ])

By construction, this is a very clean example. The remainder is zero:

In [14]: r
Out[14]: array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

Of course, you won't always get such nice results.




回答2:


The rank(x) returns the rank of matrix. In other words number of dimensions it contains. Please check whether ranks of s and f are the same before call to signal.convolve(). Otherwise you will receive an exception you quote.

I have no idea why deconvolution may return something with more dimensions than given input. This requires deeper investigation I don't have time for.



来源:https://stackoverflow.com/questions/17063775/convolution-and-deconvolution-in-python-using-scipy-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!