Reputation: 95
I'm trying to convolve a 3 dimensional values array of shape (10, 100, 100) with a gaussian of shape (10, 100, 100). When I use the convolve function I get a Value error.
def gaussian(x, mu, sigma):
g = (1./ (sigma * sqrt(2*pi))) * exp(-(x - mu)**2 / sigma**2)
return g
gauss_I = gaussian( values, mean(values), std(values) )
import numpy as np
np.convolve( values, gauss_I)
convolve(values, gauss_I)
Traceback (most recent call last):
File "", line 1, in convolve(values, gauss_I)
File "/Users/Me/Applications/anaconda/lib/python3.5/site-packages/numpy/core/numeric.py", line 1013, in convolve
return multiarray.correlate(a, v[::-1], mode)
ValueError: object too deep for desired array
I've also used the correlate function but that gives me the same error.
Upvotes: 3
Views: 6545
Reputation: 138
I have been having the same problem for some time. As already mentioned in the comments the function np.convolve
supports only 1-dimensional convolution. One alternative I found is the scipy function scipy.signal.fftconvolve
which works for N-dimensional arrays.
For example here I test the convolution for 3D arrays with shape (100,100,100)
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sps
# create 3D meshgrid and function cos(x+y)
bins = np.linspace(-10,10,100)
x, y, z = np.meshgrid(bins, bins, bins)
cos = np.cos(x+y)
print(cos.shape) # (100, 100, 100)
# plot projection of function on x-y plane
plt.title(r'$\cos(x+y)$')
plt.contourf(x[:,:,0], y[:,:,0], np.sum(cos,axis=2))
plt.colorbar()
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.show()
# perform convolution of function with itself
conv = sps.fftconvolve(cos, cos, mode='same')
print(conv.shape) # (100, 100, 100)
# plot projection of convolution on x-y plane
plt.title('numerical convolution')
plt.contourf(x[:,:,0], y[:,:,0], np.sum(conv,axis=2))
plt.colorbar()
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.show()
I obtain the following images:
Hope it is helpful!
Upvotes: 2