Skip to content

Instantly share code, notes, and snippets.

@rocking5566
Created June 15, 2018 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rocking5566/cd0ea63980391e947984e169ab1cfdc3 to your computer and use it in GitHub Desktop.
Save rocking5566/cd0ea63980391e947984e169ab1cfdc3 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
using namespace std;
typedef vector< vector<float>> matrix;
void PrintMatrix(const matrix& mat)
{
for (int i = 0, row = mat.size(); i < row; ++i)
{
for (int j = 0, col = mat[i].size(); j < col; ++j)
{
cout << mat[i][j] << "\t";
}
cout << endl;
}
}
void ResizeMatrix(matrix& mat, int row, int col)
{
mat.resize(row);
for (int i = 0; i < row; ++i)
{
mat[i].resize(col);
}
}
// 3*3, without padding
matrix convolution(const matrix& image, const matrix& kernel)
{
matrix ret;
int kernelSize = 3;
int shrink = kernelSize / 2;
// TODO - Error handle. Ex: Check image resolution
int imageRow = image.size();
int imageCol = image[0].size();
ResizeMatrix(ret, imageRow - kernelSize + 1, imageCol - kernelSize + 1);
for (int i = shrink; i < imageRow - shrink; ++i)
{
int retI = i - shrink;
for (int j = shrink; j < imageCol - shrink; ++j)
{
int retJ = j - shrink;
// TODO - Do not re-compute overlap region in each step
for (int ki = 0; ki < kernelSize; ++ki)
{
for (int kj = 0; kj < kernelSize; ++kj)
{
ret[retI][retJ] += kernel[ki][kj] * image[i - shrink + ki][j - shrink + kj];
}
}
}
}
return move(ret);
}
int main()
{
matrix image = { {1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1} };
matrix kernel = { { 0.1f, 0.1f, 0.1f },
{ 0.1f, 0.1f, 0.1f },
{ 0.1f, 0.1f, 0.1f } };
matrix result = convolution(image, kernel);
cout << "image = " << endl;
PrintMatrix(image);
cout << endl << "kernel = " << endl;
PrintMatrix(kernel);
cout << endl << "result = " << endl;
PrintMatrix(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment