商湯科技筆試演算法題(手寫卷積)
阿新 • • 發佈:2018-12-15
#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型別代替。