在c#中使用3x3中值过滤器

时间:2011-03-02 04:45:04

标签: c# image image-processing filter median

朋友您好我正在尝试将3x3中值滤波器应用于appxo 500x500的指纹图像。 我正在使用指针访问图像数据。但我真的无法弄清楚如何去做。我非常了解这个概念,但如果你帮我在代码中帮助我,那将是非常有帮助的。我在网上搜索,但我得到任何帮助。谢谢

public void medianfilter(Bitmap image)
{ 
    Byte[,] rtemp = new Byte[3, 3];
    Byte[,] gtemp = new Byte[3, 3]; 
    Byte[,] btemp = new Byte[3, 3]; 
    BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); 
    int stride = data.Stride; 
    unsafe {
           byte* imgPtr = (byte*)(void*)(data.Scan0);
           int nOffset = stride - image.Width * 3;
           for (int i = 0; i < image.Width; i++)
           { 
               for (int j = 0; j < image.Height; j++)
               { 
                   for (int x = i; x < 3 + i; x++)
                   {
                       for (int y = j; y < 3 + j; y++) {
                           rtemp[x, y] = imgPtr[0];
                           gtemp[x, y] = imgPtr[1];
                           btemp[x, y] = imgPtr[2];
                           imgPtr += 3; } } imgPtr += nOffset;
                    }
               }
           }
     }

1 个答案:

答案 0 :(得分:2)

首先,你根本不修改位图!

您需要在应用更改之前取消引用指针,然后必须解锁位图...

这是我在旧计算机图形学课程中的内容。根据需要进行修改。

unsafe
{
    //Go to first pixel, the cast is important
    byte* p = (byte*)imageData.Scan0.ToPointer();

    //For each line
    for (int y = 0; y < bmp.Height; y++)
    {
         //For each pixel (bmp.Width * 3) because jpg has R, G, and B value if the bitmap has an alpha do a *4 multiplier
         for (int x = 0; x < bmp.Width * 3; x++)
         {
                //Invert from the original image
                *p = (byte)(255 - *p);
                //Go to next pointer
                p++;
          }
          //Move pointer to the right end of the line and then go down to a new line
          //Skip the unused space
          p += offset;
     }
}
bmp.UnlockBits(imageData);
bmp.Save(path);

希望它有所帮助!