October 1, 2015
2D Convolution Source Code (conv2)
I have interested with 2D convolution in Matlab. You can check at Matlab with command conv2. I want to use this function in other language (C#), but can not get the source code in matlab conv2.m files. My friend (Herlan) search in the internet and get the algorithm for 2D convolution source code. This is algorithm 2D Convolution in C#. If you need the other algorithm, you can convert this source to other language (C/C++, VB or other) without much modification.
using System; using System.Collections.Generic; using System.Text; namespace conv2d { class Program { public static float[,] alloc2float(int row, int col) { float[,] A = null; A = new float[row, col]; return (A); } public static void free2float(float[,] A) { A = null; } public static void print2float(string sstr, float[,] A, int nrow, int ncol) { int i, j; System.Console.WriteLine(sstr); for (i = 0; i < nrow; i++) { for (j = 0; j < ncol; j++) { System.Console.Write(A[i, j].ToString() + " "); } System.Console.WriteLine(""); } System.Console.WriteLine(""); } public static float[,] flip90_idx2(float[,] A, int nrow, int ncol) { int i, j; int ii, jj; float[,] temp = alloc2float(nrow, ncol); for (i = 0; i < nrow; i++) { ii = nrow-1-i; for (j = 0; j < ncol; j++) { jj = ncol-1-j; temp[i,j] = A[ii,jj]; } } return (temp); } public static float[,]conv2(float[,]A, int r, int c, float[,] k, int m, int n) { int x, y, i, j, q, w; float[,] h = flip90_idx2(k, m, n); int centerR = Convert.ToInt32(Math.Floor((m+1)/2.0)); int centerC = Convert.ToInt32(Math.Floor((n+1)/2.0)); int left = centerC - 1; int right = n - centerC; int top = centerR - 1; int bottom = m - centerR; float[,] Rep = alloc2float(r + top + bottom, c + left + right); for (x = top; x < r + top; x++) { for (y = left; y < c + left; y++) { Rep[x, y] = A[x - top, y - left]; } } float[,] B = alloc2float(r, c); for (x = 0; x < r; x++) { for (y = 0; y < c; y++) { for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { q = x; w = y; B[x, y] = B[x, y] + (Rep[i + q, j + w] * h[i, j]); } } } } free2float(Rep); return (B); } static void Main(string[] args) { int i, j; float idx; int row1 = 3; int col1 = 4; float[,] A = alloc2float(row1, col1); idx = 1.0f; for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) { A[i, j] = idx; idx = idx + 1.0f; } } float[,] C = conv2(A, row1, col1, A, row1, col1); print2float("A", A, row1, col1); print2float("C", C, row1, col1); } } }
Copy this code to your C# project and run the program. The sample output from 2D convolution source code above is:
A 1 2 3 4 5 6 7 8 9 10 11 12 C 68 120 122 104 222 364 339 272 356 536 458 344
If you check at matlab, our conv2 source code result is same with conv2(A,A,’same’) in Matlab. Please send the comment if you have questions.