版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NichChen/article/details/83064830
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
int M, N;
int tmparr;
cin >> M >> N;
vector<vector<int> > array(N, vector<int>(M, 0));
for(int i = 0; i < N; ++i) {
for(int j = 0; j < M; ++j) {
cin >> tmparr;
array[i][j] = tmparr;
}
}
cout << "array end" << endl;
int W, H;
double tmpfilter;
cin >> W >> H;
vector<vector<double> > filter(H, vector<double>(W, 0));
for(int i = 0; i < H; ++i) {
for(int j = 0; j < W; ++j) {
cin >> tmpfilter;
filter[i][j] = tmpfilter;
}
}
cout << "filter end" << endl;
//vector<vector<unsigned char> > res(N, vector<unsigned char>(M, 0));
double tmp;
int top = -(H-1)/2;
int left = -(W-1)/2;
for(int i = 0; i < N; ++i) {
for(int j = 0; j < M; ++j) {
tmp = 0;
int boxtop = i + top;
int boxleft = j + left;
for(int k = 0; k < H; ++k) {
for(int l = 0; l < W; ++l) {
int tmpboxtop = boxtop + k;
int tmpboxleft = boxleft + l;
if (tmpboxtop < 0) tmpboxtop = -tmpboxtop;
if (tmpboxtop >= N) tmpboxtop = 2*N - 2 - tmpboxtop;
if (tmpboxleft < 0) tmpboxleft = - tmpboxleft;
if (tmpboxleft >= M) tmpboxleft = 2*M - 2 - tmpboxleft;
//cout << "tmpboxtop = " << tmpboxtop << endl;
//cout << "tmpboxleft = " << tmpboxleft << endl;
//cout << "k = " << k << endl;
//cout << "l = " << l << endl;
//cout << "array[tmpboxtop][tmpboxleft] = " << array[tmpboxtop][tmpboxleft] << endl;
//cout << "filter[k][l] = " << filter[k][l] << endl;
tmp += array[tmpboxtop][tmpboxleft] * filter[k][l];
}
}
//res[i][j] = (unsigned char)tmp;
cout << tmp << " ";
}
cout << endl;
}
system("pause");
}
padding填充后并same卷积的大体思路如上,然而题目还考了个用unsigned char存储原始图片的像素值(节省空间),在相乘的时候需要数据的转换,此代码直接用Int类型代替。