【问题标题】:Speed up pixel format conversion - BGR packed to RGB planar加快像素格式转换 - BGR 打包为 RGB 平面
【发布时间】:2015-02-16 22:48:30
【问题描述】:

从 SDK 中,我得到了像素格式 BGR 打包的图像,即BGRBGRBGR。对于另一个应用程序,我需要将此格式转换为 RGB 平面 RRRGGGBBB。我不想为这个任务使用额外的库,所以我必须使用自己的代码在格式之间进行转换。

我正在使用 C# .NET 4.5 32 位,数据位于具有相同大小的字节数组中。

现在我正在遍历数组源并将 BGR 值分配到目标数组中的适当位置,但这需要太长时间(1.3 兆像素图像需要 250 毫秒)。运行代码的处理器是 Intel Atom E680,可以访问 MMX、SSE、SSE2、SSE3、SSSE3。

不幸的是,我不了解内在函数,也无法针对 Fast method to copy memory with translation - ARGB to BGR 之类的类似问题转换代码以满足我的需求。

我目前用来在像素格式之间转换的代码是:

// the array with the BGRBGRBGR pixel data
byte[] source;
// the array with the RRRGGGBBB pixel data
byte[] result;
// the amount of pixels in one channel, width*height
int imageSize;

for (int i = 0; i < source.Length; i += 3)
{
    result[i/3] = source[i + 2]; // R
    result[i/3 + imageSize] = source[i + 1]; // G
    result[i/3 + imageSize * 2] = source[i]; // B
}

我尝试将源数组的访问分成三个循环,每个通道一个,但这并没有真正帮助。所以我愿意接受建议。

for (int i = 0; i < source.Length; i += 3)
{
    result[i/3] = source[i + 2]; // R
}

for (int i = 0; i < source.Length; i += 3)
{
    result[i/3 + imageSize] = source[i + 1]; // G
}

for (int i = 0; i < source.Length; i += 3)
{
    result[i/3 + imageSize * 2] = source[i]; // B
}

编辑:我通过像这样删除除法和乘法将其缩短到 180 毫秒,但是有没有办法让它更快?它仍然很慢,我猜是因为内存读取/写入不是非常理想。

int targetPosition = 0;
int imageSize2 = imageSize * 2;
for (int i = 0; i < source.Length; i += 3)
{
    result[targetPosition] = source[i + 2]; // R
    targetPosition++;
}

targetPosition = 0;

for (int i = 0; i < source.Length; i += 3)
{
    result[targetPosition + imageSize] = source[i + 1]; // G
    targetPosition++;
}

targetPosition = 0;

for (int i = 0; i < source.Length; i += 3)
{
    result[targetPosition + imageSize2] = source[i]; // B
    targetPosition++;
}

感谢 MBo 的回答,我能够将时间从 180 毫秒减少到 90 毫秒!代码如下:

转换器.cpp:

#include "stdafx.h"

BOOL __stdcall DllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved) {
return  TRUE;
}

const unsigned char Mask[] = { 0, 3, 6, 9, 
                           1, 4, 7, 10, 
                           2, 5, 8, 11, 
                           12, 13, 14, 15};

extern "C" __declspec(dllexport) char* __stdcall ConvertPixelFormat(unsigned char* source, unsigned char *target, int imgSize) {

_asm {
    //interleave r1g1b1 r2g2b2 r3g3b3 r4b4g4 r5b5g5 r6... to planar
    //           r1r2r3r4r5..... g1g2g3g4g5... b1b2b3b4b5...
        push edi
        push esi
        mov eax, source      //A address
        mov edx, target      //B address
        mov ecx, imgSize
        movdqu xmm5, Mask    //load shuffling mask
        mov edi, imgSize     //load interleave step
        mov esi, eax
        add esi, edi
        add esi, edi
        add esi, edi
        shr ecx, 2           //divide count by 4
        dec ecx              //exclude last array chunk
        jle Rest

    Cycle:
        movdqu xmm0, [eax]        //load 16 bytes
        pshufb xmm0, xmm5         //shuffle bytes, we are interested in 12 ones
        movd [edx], xmm0          //store 4 bytes of R
        psrldq xmm0, 4            //shift right register, now G is on the end
        movd [edx + edi], xmm0    //store 4 bytes of G to proper place
        psrldq xmm0, 4            //do the same for B
        movd [edx + 2 * edi], xmm0
        add eax, 12               //shift source index to the next portion
        add edx, 4                //shift destination index
        loop Cycle

    Rest:                       //treat the rest of array
        cmp eax, esi
        jae Finish
        mov ecx, [eax]
        mov [edx], cl           //R
        mov [edx + edi], ch     //G
        shr ecx, 16
        mov [edx + 2 * edi], cl //B
        add eax, 3
        add edx, 1
        jmp Rest

    Finish:
        pop esi
        pop edi
    }
}

C# 文件:

// Code to define the method
[DllImport("Converter.dll")]
unsafe static extern void ConvertPixelFormat(byte* source, byte* target, int imgSize);

// Code to execute the conversion
unsafe
{
    fixed (byte* sourcePointer = &source[0])
    {
        fixed (byte* resultPointer = &result[0])
        {
            ConvertPixelFormat(sourcePointer, resultPointer, imageSize);
        }
    }
}

【问题讨论】:

  • 只需测试多种方式,打印时间并选择最快的。我建议从循环内部删除除法和乘法。
  • 谢谢,我能够让它更快,但想知道是否还有办法改进它。
  • 我认为您的进场速度已达到极限。您可以通过改变方法来改进它 - 例如使用多个处理器(线程)。
  • 您需要它来保证安全吗?不安全的代码(带指针)可以吗?
  • 不需要安全。但我已经得到了一个很好的答案,其中包含令我满意的指针和 asm 代码。

标签: c# arrays image-processing intrinsics pixelformat


【解决方案1】:

我已经在 Delphi 中实现了这个交错问题并检查了内置的 asm。我没有内在函数,所以使用普通的汇编程序。
pshufb 等于 _mm_shuffle_epi8 (SSSE3 intrinsic)

在每个循环步骤中,我将 16 个字节 (r1g1b1 r2g2b2 r3g3b3 r4b4g4 r5b5g5 r6) 加载到 128 位 XMM 寄存器,将它们打乱成 (r1r2r3r4 g1g2g3g4 b1b2b3b4 xxxx) 顺序,并将 r、g、b 块保存到目标内存(忽略最后 4 个字节)。下一步加载(r5b5g5 r6g6b6 r7g7b7 ...) 等等。

注意,为了简化代码,我在第一个代码版本中没有正确处理数组的尾部。由于您可以使用此代码,因此我已进行了必要的更正。

第一版问题示例:
imgSize = 32
数组大小 = 96 字节
32/4 = 8 个周期
最后一个周期从第 84 个字节开始,读取 16 个字节到第 99 个字节 - 所以我们超出了数组范围!
我只是在这里添加了保护字节:GetMem(A, Size * 3 + 15);,但对于实际任务它可能不适用,因此值得对最后一个数组块进行特殊处理。

此代码在 i5-4670 机器上转换 200 个 1.3MP cadr 需要 967 毫秒(pascal 变体)和 140 毫秒(asm 变体)(单线程处理器本身比 Atom 680 快 6-8 倍)。速度约为 0.75 GB/秒 (pas) 和 5.4 GB/秒 (asm)

const
  Mask: array[0..15] of Byte = ( 0, 3, 6, 9,
                                 1, 4, 7, 10,
                                 2, 5, 8, 11,
                                 12, 13, 14, 15);
var
  A, B: PByteArray;
  i, N, Size: Integer;
  t1, t2: DWord;
begin
  Size := 1280 * 960 * 200;
  GetMem(A, Size * 3);
  GetMem(B, Size * 3);

  for i := 0 to Size - 1 do begin
    A[3 * i] := 1;
    A[3 * i + 1] := 2;
    A[3 * i + 2] := 3;
  end;

  t1 := GetTickCount;
  for i := 0 to Size - 1 do begin
    B[i] := A[3 * i];
    B[i + Size] := A[3 * i + 1];
    B[i + 2 * Size] := A[3 * i + 2];
  end;
  t2:= GetTickCount;

    //interleave r1g1b1 r2g2b2 r3g3b3 r4b4g4 r5b5g5 r6... to planar
    //r1r2r3r4r5..... g1g2g3g4g5... b1b2b3b4b5...
  asm
    push edi
    push esi
    mov eax, A      //A address
    mov edx, B      //B address
    mov ecx, Size
    movdqu xmm5, Mask   //load shuffling mask
    mov edi, Size       //load interleave step
    mov esi, eax
    add esi, edi
    add esi, edi
    add esi, edi
    shr ecx, 2      //divide count by 4
    dec ecx         //exclude last array chunk
    jle @@Rest

  @@Cycle:
    movdqu xmm0, [eax]   //load 16 bytes
    pshufb xmm0, xmm5    //shuffle bytes, we are interested in 12 ones
    movd [edx], xmm0     //store 4 bytes of R
    psrldq xmm0, 4        //shift right register, now G is on the end
    movd [edx + edi], xmm0   //store 4 bytes of G to proper place
    psrldq xmm0, 4            //do the same for B
    movd [edx + 2 * edi], xmm0
    add eax, 12               //shift source index to the next portion
    add edx, 4                //shift destination index
    loop @@Cycle

   @@Rest:       //treat the rest of array
    cmp eax, esi
    jae @@Finish
    mov ecx, [eax]
    mov [edx], cl   //R
    mov [edx + edi], ch  //G
    shr ecx, 16
    mov [edx + 2 * edi], cl //B
    add eax, 3
    add edx, 1
    jmp @@Rest
  @@Finish:

    pop esi
    pop edi
  end;

  Memo1.Lines.Add(Format('pas %d asm %d', [t2-t1, GetTickCount - t2]));
  FreeMem(A);
  FreeMem(B);

【讨论】:

  • 非常有帮助!它将所需时间减少了 2 倍。谢谢。
  • 由于我的图像宽度需要被8整除,所以我不需要担心数组的尾部,因为步长为4意味着它总是会处理整个数组,对吧?
  • 不,我添加了解释并进行了更正以避免潜在问题(访问冲突)。查看更正的代码(在主循环之前和之后)
【解决方案2】:

您可以尝试倒数,即int i = source.Length - 1; i &gt;=0 ; i -= 3,因此source.Length 属性在每个for 循环中只读取一次,而不是在每次迭代中。

【讨论】:

    【解决方案3】:

    我听从了 Ivan 的建议,提出了摆脱除法的改进(在 C 中实现):

        int offset = 0;
        for (int i = 0; i < ARRAYSIZE(source); i += 3) {
            offset++;
            result[offset] = source[i + 2];  // R
            result[offset + imageSize] = source[i + 1];  // G
            result[offset + imageSize * 2] = source[i];  // B
        }
    

    这在我的机器上节省了大约 40% 的运行时间。

    【讨论】:

    • 谢谢,但我的速度更快,请参阅编辑 :) 改进了不少。
    【解决方案4】:

    第一步:避免多次读取源代码(见答案https://stackoverflow.com/a/27542680/949044)。这也适用于 CPU 缓存,它目前未被充分利用:您正在读取 3 个字节中的 1 个字节,因此会丢弃 2/3ds 的缓存行。 所以它可以是这样的:

    int targetPositionR = 0;
    int targetPositionG = imageSize;
    int targetPositionB = imageSize * 2;
    for (int i = 0; i < source.Length; i += 3)
    {
        result[targetPositionB] = source[i]; // B
        result[targetPositionG] = source[i + 1]; // G
        result[targetPositionR] = source[i + 2]; // R
        targetPositionB++;
        targetPositionG++;
        targetPositionR++;
    }
    

    第二步:一次写入 4 个字节,而不是 1 个字节。但是,它需要一个额外的缓冲区和一个副本:

    int[] dwPlanar = new int[imageSize*3/4];
    int targetPositionR = 0;
    int targetPositionG = imageSize / 4;
    int targetPositionB = imageSize * 2 / 4;
    for (int i = 0; i < source.Length; i += 12)
    {
        int dwB = (source[i  ]) | (source[i+3] << 8) | (source[i+6] << 16) | (source[i+9]  << 24);
        int dwG = (source[i+1]) | (source[i+4] << 8) | (source[i+7] << 16) | (source[i+10] << 24);
        int dwR = (source[i+2]) | (source[i+5] << 8) | (source[i+8] << 16) | (source[i+11] << 24);
        dwPlanar[targetPositionB] = dwB; // B
        dwPlanar[targetPositionG] = dwG; // G
        dwPlanar[targetPositionR] = dwR; // R
        targetPositionB++;
        targetPositionG++;
        targetPositionR++;
    }
    Buffer.BlockCopy(dwPlanar,0,result,0,imageSize * 3);
    

    我想这会有所帮助,因为 c# 将减少数组边界检查,而且通常情况下,尽可能以较大的块写入是一个更好的主意。

    (免责声明:我不熟悉c#,也不知道这段代码是否能编译,它只是一个算法)。

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 2017-07-01
      相关资源
      最近更新 更多