opencvSharp 遍历Mat像素点的两种方法

一、在C#中用指针,在unsafe中运行。在生成中勾选使用不安全的代码,方法和C++完全一样,详情见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;
        }

二、用C#中的get和set方法,速度较慢

//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);
            //    }
            //}

猜你喜欢

转载自blog.csdn.net/qq_31617121/article/details/80214924