-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1-convolve_grayscale_same.py
executable file
·35 lines (32 loc) · 1.33 KB
/
1-convolve_grayscale_same.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
#!/usr/bin/env python3
"""Function that performs a valid convolution on grayscale images"""
import numpy as np
def convolve_grayscale_same(images, kernel):
"""Performs a valid 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
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]
pw = int(kw / 2)
ph = int(kh / 2)
convolved = np.zeros((m, h, w))
npad = ((0, 0), (ph, ph), (pw, pw))
imagesp = np.pad(images, pad_width=npad,
mode='constant', constant_values=0)
for i in range(h):
for j in range(w):
image = imagesp[:, i:i + kh, j:j + kw]
convolved[:, i, j] = np.sum(np.multiply(image, kernel),
axis=(1, 2))
return convolved