#include <iostream>
#include <vector>
using namespace std;
/*
5 6 3 3
1 1 1 1 1 1
1 2 2 2 2 1
2 3 3 1 2 2
1 2 2 3 4 5
5 6 6 6 3 4
1 10 1
1 20 1
1 8 1
*/
//图像卷积
int** CNN(int** image, int M, int N, int** kernel, int K, int L)
{
int** cnn = new int* [M];
int w = L / 2;
int h = K / 2;
for (int i = 1; i <= M; i++)
{
cnn[i - 1] = new int[N];
for (int j = 1; j <= N; j++)
{
cnn[i - 1][j - 1] = 0;
int beginRow = i - w;
int beginCol = j - h;
for (int x = beginRow; x <= i + w; x++)
{
for (int y = beginCol; y <= j + h; y++)
{
cnn[i - 1][j - 1] += image[x][y] * kernel[x - beginRow][y - beginCol];
}
}
if (cnn[i - 1][j - 1] < 0)
{
cnn[i - 1][j - 1] = 0;
}
else if (cnn[i - 1][j - 1] > 255)
{
cnn[i - 1][j - 1] = 255;
}
}
}
return cnn;
}
int main(int argc, char** argv)
{
int M, N, K, L;
cin >> M >> N >> K >> L;
int w = L / 2; //边界的宽度
int h = K / 2; //边界的高度
int imageRow = M + 2 * h; //扩充后的高度
int imageCol = N + 2 * w; //扩充后的宽度
int** image = new int* [imageRow]; //图像
for (int i = 0; i < imageRow; i++)
{
image[i] = new int[imageCol];
for (int j = 0; j < imageCol; j++)
{
if (i < w || j < h || i > imageRow - w - 1 || j > imageCol - h - 1)
{
image[i][j] = 0;
}
else
{
cin >> image[i][j];
}
}
}
int** kernel = new int* [K];
for (int i = 0; i < K; i++)
{
kernel[i] = new int[L];
for (int j = 0; j < L; j++)
{
cin >> kernel[i][j];
}
}
//卷积
int** cnn = CNN(image, M, N, kernel, K, L);
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
cout << cnn[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < M; i++)
{
delete[] image[i];
}
delete[] image;
for (int i = 0; i < K; i++)
{
delete[] kernel[i];
}
delete[] kernel;
for (int i = 0; i < M; i++)
{
delete[] cnn[i];
}
delete[] cnn;
return 0;
}
网友评论