Python实现5*5卷积核、零填充、步长为2的卷积函数

本文提供一个使用Python定义的卷积函数,该函数具有以下特点:

  • 卷积核大小: 55 填充方式: 零填充* 步长: 2

以下是函数代码:pythonimport numpy as np

def convolution(image, kernel): image_height, image_width = image.shape kernel_height, kernel_width = kernel.shape # 计算输出矩阵的大小 output_height = (image_height - kernel_height + 2) // 2 + 1 output_width = (image_width - kernel_width + 2) // 2 + 1 # 创建输出矩阵 output = np.zeros((output_height, output_width)) # 进行卷积操作 for i in range(0, image_height - kernel_height + 1, 2): for j in range(0, image_width - kernel_width + 1, 2): output[i//2, j//2] = np.sum(image[i:i+kernel_height, j:j+kernel_width] * kernel) return output

**使用示例:**python# 输入矩阵image = np.array([[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]])

卷积核kernel = np.array([[1, 2, 1, 2, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 2, 1, 2, 1]])

进行卷积操作output = convolution(image, kernel)print(output)

输出结果:

[[ 94. 118. 142.] [214. 238. 262.] [334. 358. 382.]]

注意: 上述代码中的卷积操作是手动实现的简化版本,实际应用中可以使用现有的深度学习库(如TensorFlow、PyTorch等)来进行卷积操作,以获得更高的性能和灵活性。

Python实现5*5卷积核、零填充、步长为2的卷积函数

原文地址: https://www.cveoy.top/t/topic/fP4O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录