Matlab实现二维数据卷积

实现代码:

% 二维卷积操作卷积操作

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)


参考:

二维卷积的原理与手动编程实现

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值