二维数组卷积
代码根据二维矩阵与二维矩阵之间的卷积设计
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int rows, columns;//待处理矩阵行数,列数
int filter_rows, filter_columns;//卷积核矩阵行数,列数
int filter_m, filter_n;
double data_1, sum;
filter_m = (filter_rows - 1) / 2;
filter_n = (filter_columns - 1) / 2;
vector<vector<double> > observe(rows, vector<double>(columns));
vector<vector<double> > filter(filter_rows, vector<double>(filter_columns));
vector<vector<double> > data(rows, vector<double>(columns));
FILE * fp_observe, *fp_filter;
char filename_data[256], filename_data1[256];
//导入数据
printf("\n请输入待处理矩阵文件名 :: \n---> ");
scanf("%s", &filename_data);
if ((fp_observe = fopen(filename_data, "r")) == NULL)
{
printf("\nSorry!\n文件打开失败 \"%s\".\n", filename_data);
return -1;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
fscanf(fp_observe, "%lf \n", &observe[i][j]);
}
}
fclose(fp_observe);
printf("\n请输入卷积核矩阵的文件名 :: \n---> ");
scanf("%s", &filename_data1);
if ((fp_filter = fopen(filename_data1, "r")) == NULL)
{
printf("\nSorry!\n文件打开失败 \"%s\".\n", filename_data1);
return -1;
}
for (int i = 0; i < filter_rows; i++) {
for (int j = 0; j < filter_columns; j++) {
fscanf(fp_filter, "%lf \n", &filter[i][j]);
}
}
fclose(fp_filter);
//二维数组卷积
for (int i = 0; i<rows; i++) {//初始化
for (int j = 0; j<columns; j++) {
sum = 0.0;
for (int m = -filter_m; m <= filter_m; m++) {
for (int n = -filter_n; n <= filter_n; n++) {
if (((i - m) < 0) || ((j - n) < 0)) {
data_1 = 0.0;
}
else if (((i - m) >= rows) || ((j - n) >= columns)) {
data_1 = 0.0;
}
else {
data_1 = filter[(m + filter_m)][(n + filter_n)] * observe[i - m][j - n];
}
sum = sum + data_1;
}
}
data[i][j] = sum;
}
}
printf("\n输出卷积结果 :: \n---> ");
//按行输出
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%lf ", data[i][j]);
}
printf("\n");
}
return 0;
}