@@ -14,7 +14,7 @@ def convolve(input, kernel):
14
14
Returns
15
15
-------
16
16
output : numpy.ndarray
17
- output matrix, it is not cropped
17
+ output matrix, shape is the same as input
18
18
19
19
Raises
20
20
------
@@ -23,31 +23,28 @@ def convolve(input, kernel):
23
23
'''
24
24
if kernel .shape [0 ] % 2 != 1 or kernel .shape [1 ] % 2 != 1 :
25
25
raise ValueError ("Only odd dimensions on filter supported" )
26
- # s_mid and t_mid are number of pixels between the center pixel
27
- # and the edge, ie for a 5x5 filter they will be 2.
28
- #
29
- # The output size is calculated by adding s_mid, t_mid to each
30
- # side of the dimensions of the input image.
31
- s_mid = kernel .shape [0 ] // 2
32
- t_mid = kernel .shape [1 ] // 2
33
- x_max = input .shape [0 ] + 2 * s_mid
34
- y_max = input .shape [1 ] + 2 * t_mid
35
- # Allocate result image.
36
- output = np .zeros ([x_max , y_max ], dtype = input .dtype )
37
- # Do convolution
38
- for x in range (x_max ):
39
- for y in range (y_max ):
40
- # Calculate pixel value for h at (x,y). Sum one component
41
- # for each pixel (s, t) of the filter kernel.
42
- s_from = max (s_mid - x , - s_mid )
43
- s_to = min ((x_max - x ) - s_mid , s_mid + 1 )
44
- t_from = max (t_mid - y , - t_mid )
45
- t_to = min ((y_max - y ) - t_mid , t_mid + 1 )
46
- value = 0
47
- for s in range (s_from , s_to ):
48
- for t in range (t_from , t_to ):
49
- v = x - s_mid + s
50
- w = y - t_mid + t
51
- value += kernel [s_mid - s , t_mid - t ]* input [v , w ]
52
- output [x , y ] = value
26
+ # kernel_row_mid and kernel_col_mid are number of elements between the
27
+ # center elements # and the edge, i.e., for a 5x5 filter they will be 2.
28
+ kernel_row_mid = kernel .shape [0 ]// 2
29
+ kernel_col_mid = kernel .shape [1 ]// 2
30
+ # Allocate result input.
31
+ output = np .empty_like (input )
32
+ # Do convolution.
33
+ for row in range (input .shape [0 ]):
34
+ min_kernel_row = max (0 , kernel_row_mid - row )
35
+ max_kernel_row = min (kernel .shape [0 ],
36
+ kernel_row_mid + input .shape [0 ] - row )
37
+ for col in range (input .shape [1 ]):
38
+ min_kernel_col = max (0 , kernel_col_mid - col )
39
+ max_kernel_col = min (kernel .shape [1 ],
40
+ kernel_col_mid + input .shape [1 ] - col )
41
+ value = 0.0
42
+ # i and j are the kernel images
43
+ for i in range (min_kernel_row , max_kernel_row ):
44
+ for j in range (min_kernel_col , max_kernel_col ):
45
+ # k and l are the image indices
46
+ k = row - kernel_row_mid + i
47
+ l = col - kernel_col_mid + j
48
+ value += kernel [i , j ]* input [k , l ]
49
+ output [row , col ] = value
53
50
return output
0 commit comments