3

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.

8
  • Please supply the entire error message: the trace-back is important to people who know innards of the support packages. Commented Mar 30, 2017 at 16:31
  • The docs for np.convolve say: convolution of two one-dimensional sequences. Commented Mar 30, 2017 at 16:38
  • Full stack won't help here. convolve calls core.multiarray.correlate right away, and that is built-in (i.e. compiled). This is a usage error - wrong dimensions for the inputs. Commented Mar 30, 2017 at 16:40
  • You might want to look at scipy.ndimage.convolve Commented Mar 30, 2017 at 17:25
  • I've just been looking into that but it makes my kernel crash repeatedly Commented Mar 30, 2017 at 17:34

1 Answer 1

2

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:

cos

convolution

Hope it is helpful!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.