Guest User

Untitled

a guest
Jun 17th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5. typedef vector< vector<float>> matrix;
  6.  
  7. void PrintMatrix(const matrix& mat)
  8. {
  9. for (int i = 0, row = mat.size(); i < row; ++i)
  10. {
  11. for (int j = 0, col = mat[i].size(); j < col; ++j)
  12. {
  13. cout << mat[i][j] << "\t";
  14. }
  15.  
  16. cout << endl;
  17. }
  18. }
  19.  
  20. void ResizeMatrix(matrix& mat, int row, int col)
  21. {
  22. mat.resize(row);
  23.  
  24. for (int i = 0; i < row; ++i)
  25. {
  26. mat[i].resize(col);
  27. }
  28. }
  29.  
  30. // 3*3, without padding
  31. matrix convolution(const matrix& image, const matrix& kernel)
  32. {
  33. matrix ret;
  34. int kernelSize = 3;
  35. int shrink = kernelSize / 2;
  36.  
  37. // TODO - Error handle. Ex: Check image resolution
  38. int imageRow = image.size();
  39. int imageCol = image[0].size();
  40. ResizeMatrix(ret, imageRow - kernelSize + 1, imageCol - kernelSize + 1);
  41.  
  42. for (int i = shrink; i < imageRow - shrink; ++i)
  43. {
  44. int retI = i - shrink;
  45. for (int j = shrink; j < imageCol - shrink; ++j)
  46. {
  47. int retJ = j - shrink;
  48. // TODO - Do not re-compute overlap region in each step
  49. for (int ki = 0; ki < kernelSize; ++ki)
  50. {
  51. for (int kj = 0; kj < kernelSize; ++kj)
  52. {
  53. ret[retI][retJ] += kernel[ki][kj] * image[i - shrink + ki][j - shrink + kj];
  54. }
  55. }
  56. }
  57. }
  58. return move(ret);
  59. }
  60.  
  61. int main()
  62. {
  63. matrix image = { {1, 0, 0, 0},
  64. {0, 1, 0, 0},
  65. {0, 0, 1, 0},
  66. {0, 0, 0, 1} };
  67.  
  68. matrix kernel = { { 0.1f, 0.1f, 0.1f },
  69. { 0.1f, 0.1f, 0.1f },
  70. { 0.1f, 0.1f, 0.1f } };
  71.  
  72. matrix result = convolution(image, kernel);
  73.  
  74. cout << "image = " << endl;
  75. PrintMatrix(image);
  76.  
  77. cout << endl << "kernel = " << endl;
  78. PrintMatrix(kernel);
  79.  
  80. cout << endl << "result = " << endl;
  81. PrintMatrix(result);
  82. }
Add Comment
Please, Sign In to add comment