#include <vector>
#include <cmath>
#include<iostream>
using namespace std;
// 定义卷积核大小
const int kernel_size = 3;
// 定义卷积函数
std::vector<std::vector<float>> conv2d(const std::vector<std::vector<float>>& input, const std::vector<std::vector<float>>& kernel) {
// 计算输出大小
int output_width = input.size() - kernel_size + 1;
int output_height = input[0].size() - kernel_size + 1;
// 初始化输出矩阵
std::vector<std::vector<float>> output(output_width, std::vector<float>(output_height, 0));
// 遍历输入矩阵
for (int i = 0; i < output_width; ++i) {
for (int j = 0; j < output_height; ++j) {
// // 计算卷积核在输入矩阵上的位置
// int kernel_i = i;
// int kernel_j = j;
// 遍历卷积核
for (int k = 0; k < kernel_size; ++k) {
for (int l = 0; l < kernel_size; ++l) {
// 计算输入矩阵上的位置
int input_i = i + k;
int input_j = j + l;
// 计算卷积核和输入矩阵对应元素的乘积
output[i][j] += input[input_i][input_j] * kernel[k][l];
}
}
}
}
return output;
}
int main() {
// 定义输入矩阵
std::vector<std::vector<float>> input = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
// 定义卷积核
std::vector<std::vector<float>> kernel = {
{-1, 0, 1},
{-2, 0, 2},
{-1, 0, 1}
};
// 调用卷积函数
std::vector<std::vector<float>> output = conv2d(input, kernel);
// 打印输出矩阵
for (const auto& row : output) {
for (const auto& value : row) {
std::cout << value << " ";
}
std::cout << std::endl;
}
return 0;
}
代码解释
代码首先计算输出矩阵的大小,然后初始化输出矩阵。接着,代码遍历输入矩阵,对于每个位置,计算卷积核在输入矩阵上的位置,然后遍历卷积核,计算卷积核和输入矩阵对应元素的乘积,并将结果累加到输出矩阵的对应位置上。
具体来说,代码首先计算输出矩阵的大小,即输入矩阵的大小减去卷积核的大小再加一。然后,代码初始化输出矩阵,将其所有元素设置为零。接着,代码遍历输入矩阵,对于每个位置,计算卷积核在输入矩阵上的位置,然后遍历卷积核,计算卷积核和输入矩阵对应元素的乘积,并将结果累加到输出矩阵的对应位置上。最后,代码返回输出矩阵。