-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path3-convolve_grayscale.py
executable file
·57 lines (54 loc) · 2.23 KB
/
3-convolve_grayscale.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python3
"""Function that performs a valid convolution
on grayscale images with custom padding"""
import numpy as np
def convolve_grayscale(images, kernel, padding='same', stride=(1, 1)):
"""Performs a convolution on grayscale images
Args:
images: `numpy.ndarray` with shape (m, h, w)
containing multiple grayscale images
m: `int`, is the number of images
h: `int`, is the height in pixels of the images
w: `int`, is the width in pixels of the images
kernel: `numpy.ndarray` with shape (kh, kw)
containing the kernel for the convolution
kh: `int`, is the height of the kernel
kw: `int`, is the width of the kernel
padding: `tuple` of (ph, pw), ‘same’, or ‘valid’
if `tuple`:
ph: `int` is the padding for the height of the image
pw: `int` is the padding for the width of the image
if ‘same’, performs a same convolution
if ‘valid’, performs a valid convolution
stride is a tuple of (sh, sw)
sh: `int`, is the stride for the height of the image
sw: `int`, is the stride for the width of the image
Returns:
output: `numpy.ndarray` containing the convolved images
"""
m, h, w = images.shape[0], images.shape[1], images.shape[2]
kh, kw = kernel.shape[0], kernel.shape[1]
sh, sw = stride[0], stride[1]
if padding == 'same':
ph = int(((w - 1) * sw + kw - w) / 2) + 1
pw = int(((h - 1) * sh + kh - h) / 2) + 1
elif padding == 'valid':
ph = 0
pw = 0
else:
pw = padding[1]
ph = padding[0]
nw = int(((w - kw + (2 * pw)) / sw) + 1)
nh = int(((h - kh + (2 * ph)) / sh) + 1)
convolved = np.zeros((m, nh, nw))
npad = ((0, 0), (ph, ph), (pw, pw))
imagesp = np.pad(images, pad_width=npad,
mode='constant', constant_values=0)
for i in range(nh):
x = i * stride[0]
for j in range(nw):
y = j * sw
image = imagesp[:, x:x + kh, y:y + kw]
convolved[:, i, j] = np.sum(np.multiply(image, kernel),
axis=(1, 2))
return convolved