|
| 1 | +import numpy as np |
| 2 | +cimport numpy as cnp |
| 3 | +cnp.import_array() |
| 4 | + |
| 5 | +DTYPE = np.float64 |
| 6 | +ctypedef cnp.float64_t DTYPE_t |
| 7 | + |
| 8 | +def convolve(cnp.ndarray input, cnp.ndarray kernel): |
| 9 | + '''Naive convolution of matrices input and kernel |
| 10 | +
|
| 11 | + Parameters |
| 12 | + ---------- |
| 13 | + input : numpy.ndarray |
| 14 | + input matrix |
| 15 | + kernel : numpy.ndarray |
| 16 | + filter kernel matrix, dimensions must be odd |
| 17 | +
|
| 18 | + Returns |
| 19 | + ------- |
| 20 | + output : numpy.ndarray |
| 21 | + output matrix, it is not cropped |
| 22 | +
|
| 23 | + Raises |
| 24 | + ------ |
| 25 | + ValueError |
| 26 | + if dimensions of kernel are not odd |
| 27 | + ''' |
| 28 | + if kernel.shape[0] % 2 != 1 or kernel.shape[1] % 2 != 1: |
| 29 | + raise ValueError("Only odd dimensions on filter supported") |
| 30 | + assert input.dtype == DTYPE and kernel.dtype == DTYPE |
| 31 | + # s_mid and t_mid are number of pixels between the center pixel |
| 32 | + # and the edge, ie for a 5x5 filter they will be 2. |
| 33 | + # |
| 34 | + # The output size is calculated by adding s_mid, t_mid to each |
| 35 | + # side of the dimensions of the input image. |
| 36 | + cdef int s_mid = kernel.shape[0] // 2 |
| 37 | + cdef int t_mid = kernel.shape[1] // 2 |
| 38 | + cdef int x_max = input.shape[0] + 2 * s_mid |
| 39 | + cdef int y_max = input.shape[1] + 2 * t_mid |
| 40 | + # Allocate result image. |
| 41 | + cdef cnp.ndarray output = np.zeros([x_max, y_max], dtype=input.dtype) |
| 42 | + # Do convolution |
| 43 | + cdef int x, y, s, t, v, w |
| 44 | + cdef int s_from, s_to, t_from, t_to |
| 45 | + cdef DTYPE_t value |
| 46 | + for x in range(x_max): |
| 47 | + for y in range(y_max): |
| 48 | + # Calculate pixel value for h at (x,y). Sum one component |
| 49 | + # for each pixel (s, t) of the filter kernel. |
| 50 | + s_from = max(s_mid - x, -s_mid) |
| 51 | + s_to = min((x_max - x) - s_mid, s_mid + 1) |
| 52 | + t_from = max(t_mid - y, -t_mid) |
| 53 | + t_to = min((y_max - y) - t_mid, t_mid + 1) |
| 54 | + value = 0 |
| 55 | + for s in range(s_from, s_to): |
| 56 | + for t in range(t_from, t_to): |
| 57 | + v = x - s_mid + s |
| 58 | + w = y - t_mid + t |
| 59 | + value += kernel[s_mid - s, t_mid - t]*input[v, w] |
| 60 | + output[x, y] = value |
| 61 | + return output |
0 commit comments