1. Use pointers in C# and run in unsafe. Check Use unsafe code in the generation. The method is exactly the same as that of C++. For details, see Traversing Pixels in C++.
public unsafe static Mat ConvolutionImage(Mat img, double[,] k, int offsetH, int offsetW, int height, int width)
{
Mat src = new Mat(img, new Rect(offsetW, offsetH, width, height));
Mat dst = new Mat(src.Size(), MatType.CV_8UC1, new Scalar(0));
int rows = src.Height, cols = src.Width;
int v;
for(int i = 1; i < rows -1; i++)
{
IntPtr a = dst.Ptr(i);
byte* b = (byte*)a.ToPointer();
for (int j = 1; j < cols - 1; j++)
{
b[j] = 200;
}
}
//for(int i = 1; i < rows -1; i++)
//{
// for(int j = 1; j < cols -1; j++)
// {
// v = (int)Math.Abs(k[0, 0] * src.Get<byte>(i - 1, j - 1) + k[0, 2] * src.Get<byte>(i - 1, j + 1) + k[0, 1] * src.Get<byte>(i - 1, j) + k[2, 1] * src.Get<byte>(i + 1, j));
// v =(int)(255 - 2 * v + 2 * k[1, 1] * src.Get<byte>(i, j));
// v = v > 0 ? v : 0;
// v = v < 255 ? v : 255;
// dst.Set(i, j, v);
// }
//}
return dst;
}
Second, using the get and set methods in C#, the speed is slower
//for(int i = 1; i < rows -1; i++)
//{
// for(int j = 1; j < cols -1; j++)
// {
// v = (int)Math.Abs(k[0, 0] * src.Get<byte>(i - 1, j - 1) + k[0, 2] * src.Get<byte>(i - 1, j + 1) + k[0, 1] * src.Get<byte>(i - 1, j) + k[2, 1] * src.Get<byte>(i + 1, j));
// v =(int)(255 - 2 * v + 2 * k[1, 1] * src.Get<byte>(i, j));
// v = v > 0 ? v : 0;
// v = v < 255 ? v : 255;
// dst.Set(i, j, v);
// }
//}