C# Roberts 算法图像边缘检测-学习笔记

转载请注明出处  by GshMissZL,

我自己通过《C#数字图像处理算法典型实例》这本书学习,Roberts这个算法我按照书上输入之后不能很好的处理图像,下面是一些修改的部分。这是全部代码的一部分,给其他遇到同样问题的人提供个思路,(初学者,忘指正)

 

                    Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
                    System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect,
                        System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
                    IntPtr ptr = bmpData.Scan0;
                   // int bytes = curBitmap.Width * curBitmap.Height ;//原来的代码,宽度不合理   W*H*3
                    int bytes1 = bmpData.Stride * curBitmap.Height;//改为用 扫描宽度*height 
                    byte[] grayValues = new byte[bytes1];
                    System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes1);
                    int thresholding = operatorMask.GetThresholding;//得到阈值,
                    byte flagMask = operatorMask.GetMask;//选择算法
                    double[] tempArray = new double[bytes1];//用双浮点运算
                    double gradX, gradY, grad;
                    switch (flagMask)//只写了 flagMask=0 时的代码
                    {
                        case 0:
                            //Roberts
                           0 1    1 0
                          -1 0   0 -1
                            for (int i = 0; i +1< curBitmap.Height; i++)
                            {
                                for (int j = 0; j+1  < bmpData.Stride; j+=3)//每个像素占三个字节
                                {
                                    gradX = grayValues[i* bmpData.Stride
                                        + j +1] 
                                        - grayValues[(i + 1) * bmpData.Stride + j];
                                    gradY = grayValues[i * bmpData.Stride + j] 
                                        - grayValues[(i+1)*bmpData.Stride+j+1];
                                    grad = Math.Sqrt(gradX * gradX + gradY * gradY);
                                    tempArray[i * bmpData.Stride + j] 
					 = tempArray[i * bmpData.Stride + j+1] 
  					 =tempArray[i * bmpData.Stride + j+2] 
				         = grad;
                                }
                            }
                            break;
                    }
                    for (int i = 0; i < bytes1-2; i+=3)
                    {
                      if(tempArray[i]<thresholding)
                           grayValues[i] =grayValues[i+1]=grayValues[i+2]=0;
                        if (tempArray[i] >= thresholding)
                            grayValues[i] = grayValues[i + 1] = grayValues[i + 2]=255;
                    }
                    System.Runtime.InteropServices.Marshal.Copy(grayValues, 0,ptr,bytes1);
                    curBitmap.UnlockBits(bmpData);


你可能感兴趣的:(C#,数字图像处理,边缘检测,Roberts)