本文介绍了使用BitmapData和C#中的指针进行快速位图修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从某些相机(RAW数据数组)捕获数据.

I am capturing data from some camera (array of RAW data).

然后我要根据调色板将此数据映射到RGB值.

Then I'm mapping this data to RGB values according to color palette.

我需要尽快映射它,所以我使用BitmapDdata并使用指针在不安全的代码段中编辑像素.

I need to map it as fast as possible, so I use BitmapDdata and edit pixels in unsafe piece of code using pointers.

public void dataAcquired(int[] data)
{
    Bitmap bmp = new Bitmap(width, height);
    BitmapData data = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

    for (int i = 0; i < data.Length; i++)
    {
        int x = i % bmp.Width;
        int y = i / bmp.Width;
        Rgb rgb = mapColors[data[i]];

        unsafe
        {
            byte* ptr = (byte*)data.Scan0;
            ptr[(x * 3) + y * data.Stride] = rgb.b;
            ptr[(x * 3) + y * data.Stride + 1] = rgb.g;
            ptr[(x * 3) + y * data.Stride + 2] = rgb.r;
        }
    }
    bmp.UnlockBits(data);
}

我正在为每个传入的帧执行此操作.它可以正常工作,但是对于320x240像素,每帧仍然需要30毫秒左右的时间.

And I'm doing this for every incoming frame. It works fine, but it still takes something like 30ms for each frame for 320x240 pixels.

是否可以使其更快?也许我只能对内存中的数据进行一次锁定/解锁,但是对此我不确定.

Is it possible to make it even more faster? Maybe I couldlock/unlock data in memory only once, but I'm not sure about this.

推荐答案

您可以使它们成为循环计数器,而不是为每个像素计算x和y,如下所示:

Instead of calculating x and y for each pixel, you could make them loop counters, like this:

for( y = 0;  y < bmp.Height;  y++ )
    for( x = 0;  x < bmp.Width;  x++ )

更好的是,将x和y完全切掉,只是不断增加ptr指针,而不是重新计算每个像素与ptr指针的偏移量三次.

Better yet, ditch x and y altogether and just keep incrementing the ptr pointer instead of recalculating an offset from the ptr pointer three times per pixel.

尝试一下(警告:我尚未检查.)

Try this (warning: I have not checked it.)

public void dataAcquired()
{
    Bitmap bmp = new Bitmap(width, height);
    BitmapData data = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    unsafe
    {
        int i = 0;
        byte* ptr = (byte*)data.Scan0;
        for( int y = 0;  y < bmp.Height;  y++ )
        {
            byte* ptr2 = ptr;
            for( int x = 0;  x < bmp.Width;  x++ )
            {
                Rgb rgb = mapColors[data[i++]];
                *(ptr2++) = rgb.b;
                *(ptr2++) = rgb.g;
                *(ptr2++) = rgb.r;
            }
            ptr += data.Stride;
        }
    }
    bmp.UnlockBits(data);
}

这篇关于使用BitmapData和C#中的指针进行快速位图修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:46
查看更多