c++ 二维数组卷积

二维数组卷积

代码根据二维矩阵与二维矩阵之间的卷积设计

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值