Speed up Matrix Addition in C#

前端 未结 15 1165
北荒
北荒 2021-02-05 22:48

I\'d like to optimize this piece of code :

public void PopulatePixelValueMatrices(GenericImage image,int Width, int Height)
{            
        for (int x = 0;         


        
15条回答
  •  生来不讨喜
    2021-02-05 23:12

    Read this article which also has some code and mentions about the slowness of GetPixel.

    link text

    From the article this is code to simply invert bits. This shows you the usage of LockBits as well.

    It is important to note that unsafe code will not allow you to run your code remotely.

    public static bool Invert(Bitmap b)
    {
    
    BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), 
                                   ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); 
    
    int stride = bmData.Stride; 
    System.IntPtr Scan0 = bmData.Scan0; 
    unsafe 
    { 
        byte * p = (byte *)(void *)Scan0;
        int nOffset = stride - b.Width*3; 
        int nWidth = b.Width * 3;
        for(int y=0;y < b.Height;++y)
        {
            for(int x=0; x < nWidth; ++x )
            {
                p[0] = (byte)(255-p[0]);
                ++p;
            }
            p += nOffset;
        }
    }
    
    b.UnlockBits(bmData);
    
    return true;
    

    }

提交回复
热议问题