conv2 python

Solutions on MaxInterview for conv2 python by the best coders in the world

showing results for - "conv2 python"
Lukas
27 May 2020
1import numpy as np
2from scipy.ndimage.filters import convolve
3
4def conv2(x,y,mode='same'):
5    """
6    Emulate the function conv2 from Mathworks.
7
8    Usage:
9
10    z = conv2(x,y,mode='same')
11
12    TODO: 
13     - Support other modes than 'same' (see conv2.m)
14    """
15
16    if not(mode == 'same'):
17        raise Exception("Mode not supported")
18
19    # Add singleton dimensions
20    if (len(x.shape) < len(y.shape)):
21        dim = x.shape
22        for i in range(len(x.shape),len(y.shape)):
23            dim = (1,) + dim
24        x = x.reshape(dim)
25    elif (len(y.shape) < len(x.shape)):
26        dim = y.shape
27        for i in range(len(y.shape),len(x.shape)):
28            dim = (1,) + dim
29        y = y.reshape(dim)
30
31    origin = ()
32
33    # Apparently, the origin must be set in a special way to reproduce
34    # the results of scipy.signal.convolve and Matlab
35    for i in range(len(x.shape)):
36        if ( (x.shape[i] - y.shape[i]) % 2 == 0 and
37             x.shape[i] > 1 and
38             y.shape[i] > 1):
39            origin = origin + (-1,)
40        else:
41            origin = origin + (0,)
42
43    z = convolve(x,y, mode='constant', origin=origin)
44
45    return z
46