实现代码:
% 二维卷积操作卷积操作
clc
clear
% 3*3 卷积核必须是方阵,且行列数为奇数
x = [-1 -2 -3;
0 0 0;
1 2 3];
% 5*5
data = [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];
pre_conv = conv2(data, x, 'same')
x_conv_ker = rot90(rot90(x));
% 卷积核的大小
[ker_row, ker_col] = size(x_conv_ker);
% 图像数据的大小
[img_row, img_col] = size(data);
% 卷积核中心元素
ker_center_row = round(ker_row/2); % round:四舍五入取整
ker_center_col = round(ker_col/2);
ker_center = x_conv_ker(ker_center_row, ker_center_col);
% 增广图像原始数据
data_append = zeros(img_row + ker_row - 1, img_col + ker_col - 1);
data_append(ker_center_row : ker_center_row + img_row - 1, ker_center_col : ker_center_col + img_col - 1) = data;
% 计算增广后的图像数据大小
[append_row, append_col] = size(data_append);
% 卷积
conv_result = zeros(append_row, append_col);
for m = ker_center_row:ker_center_row + img_row - 1
for n = ker_center_col:ker_center_col + img_col - 1
data_mid = data_append(m-(ker_center_row - 1) : m+(ker_center_row - 1), n-(ker_center_row - 1):n+(ker_center_row-1));
conv_operation = sum(x_conv_ker.*data_mid);
conv_result(m, n) = sum(conv_operation(:));
end
end
% 删去之前增广的0边
conv_result = conv_result(ker_center_row : ker_center_row + img_row - 1, ker_center_col : ker_center_col + img_col - 1)
参考: