Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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);
- }
Add Comment
Please, Sign In to add comment