使用scipy.signal在Python中进行卷积和反卷积 [英] Convolution and Deconvolution in Python using scipy.signal

查看:633
本文介绍了使用scipy.signal在Python中进行卷积和反卷积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对音频样本进行(反)卷积。
我有一个示例 s ,并且同一示例带有 s_f 并添加了一些过滤器。两个样本都表示为numpy数组。
我想对它们进行反卷积,以获得代表孤立过滤器 f 的数组。一旦这样做,我应该能够使用 s f 的卷积来再现 s_f

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.

这是代码:

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?

非常感谢,
omer

Thanks much, omer

推荐答案

deconvolve 返回两个数组,即商和余数。因此,尝试:

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

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

长期以来, deconvolve 尚无适当的文档字符串,但其中有一个文档字符串。 github上的master分支: https://github.com/ scipy / scipy / blob / master / scipy / signal / signaltools.py#L731

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

文档字符串显示了反卷积。这是另一个( sig scipy.signal np numpy ):

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

要进行反卷积的信号是 z ,并且滤波器系数在 filter 中:

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])

应用解卷积

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

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

将过滤器应用于 q 以验证我们是否返回了 z

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.

这篇关于使用scipy.signal在Python中进行卷积和反卷积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆