# 卷積計算過程 by 邱逸庭

YTC
c_cpp
2 years ago
2.5 kB
0
Indexable
Never
```//
//  main.cpp
//  codehomework #11
//
//  Created by YTC on 2022/5/18.
//

#include <iostream>
#include <vector>
using namespace std;

int main(int argc, const char * argv[]) {
int const map = 6;
int F [map*map] = { 18, 16, 12, 8, 5, 0,
15, 18, 18, 10, 2, 8,
12, 10,20,5, -6, 4,
5, 6, 10,19, 10,3,
0, 2, 7, 9, 18, 1,
4 ,6, 5 , 2, 0, 17};
int const kernel = 3;
int C [kernel*kernel] = { 0, -1, 0,
-1, 4, -1
,0, -1, 0 };

int const outm = map - kernel + 1;

int const conH = map * map;
int const conW = kernel * kernel;

float container[conW * conH] = { 0 };

for(int i = 0 ; i < outm; i++){
for(int j = 0 ; j < outm;j++){
int wh = i * outm * conW + j* conW;

int col1 = i * map + j ;
container[wh] = F[col1];
container[wh+1] = F[col1 + 1];
container[wh+2] = F[col1 + 2];

int col2 = (i+1) * map + j;
container[wh + 3] = F[col2];
container[wh + 4] = F[col2 + 1];
container[wh + 5] = F[col2 + 2];

int col3 = (i+2) * map + j;
container[wh + 6] = F[col3];
container[wh + 7] = F[col3 + 1];
container[wh + 8] = F[col3 + 2];
}
}

vector<int> c;

for(int i = 0 ; i < outm ; i++){
for(int j = 0 ; j < outm ; j++)
{
int a = 0 ;
int wh = i * outm * conW + j * conW;
for(int m = 0 ; m < conW ; m++){
a += container[wh + m]* C[m];
}
c.push_back(a);
}
}

cout<< "Convolved matrix: "<< endl;

for(int i = 0 ; i < map ; i++){

for(int j = 0 ; j < map ; j++){
cout << F[i * map +j] << " ";

}
cout<< endl;
}
cout << endl;

cout << "Kernel matrix: " << endl;
for(int i = 0 ; i < kernel; i++){
for(int j = 0 ; j < kernel ; j++){
cout << C[i*kernel + j] << " ";
}
cout << endl;
}
cout << endl;

cout << "The result matrix: " <<endl;

for(int i = 0 ; i < outm ; i++){
for(int j = 0 ; j < outm ; j++){
cout<< c[i * outm + j ]<< " ";
}
cout << endl;
}
return 0;
}
```