import matplotlib.pyplot as plt
import numpy as np
def convolution(image, op):
h = image.shape[0] - op.shape[0] + 1
w = image.shape[1] - op.shape[1] + 1
res = np.zeros(shape=(h, w))
for hh in range(h):
for ww in range(w):
win = image[hh:hh + op.shape[0], ww:ww + op.shape[1]]
res[hh][ww] = np.sum(np.multiply(win, op))
return res
if __name__ == '__main__':
# fig, ax = plt.subplots(1, 2, figsize=(10, 10))
# plt.sca(ax[(0,)])
# from PIL import Image
#
# image = np.array(Image.open('img.png'))
# plt.imshow(image)
# plt.sca(ax[(1,)])
image = np.array(
[
[4, 4, 0, 0],
[3, 3, 0, 0],
[3, 3, 0, 0],
[1, 1, 0, 0]
]
)
op = np.array(
[
[1, 0, -1],
[1, 0, -1],
[1, 0, -1]
])
res = convolution(image, op)
print(res)
# plt.imshow(res)
# plt.show()
手动实现convolution
最新推荐文章于 2024-08-14 12:00:04 发布