10/11/12 bit coded pixels in WPF

I need to use a mono-chromatic camera API which states in its manual the following:

Each pixel (10, 11 or 12 bits) is coded on 16 bits. Pixel value is placed on the LSB of the 16 bits.

I will use WPF/C# with Bitmap; or I might use WPF with OpenGL. I don't have expertise in any.

Is the only way to down convert the pixels to 8-bit?(here someone mentions)

I came across the closest question here but with no answers.


Solution 1:

You may use a BitmapSource with Format set to PixelFormats.Gray16.

Then convert the source pixel values to 16-bit pixel values like this:

public static int ConvertTo16Bit(int pixelValue, int sourceBitsPerPixel)
{
    const int maxTargetValue = (1 << 16) - 1;
    int maxSourceValue = (1 << sourceBitsPerPixel) - 1;

    return maxTargetValue * pixelValue / maxSourceValue;
}

Convert pixel buffer arrays like this:

public static void ConverTo16Bit(
    ushort[] target, ushort[] source, int sourceBitsPerPixel)
{
    const int maxTargetValue = (1 << 16) - 1;
    int maxSourceValue = (1 << sourceBitsPerPixel) - 1;

    for (int i = 0; i < source.Length; i++)
    {
        target[i] = (ushort)(maxTargetValue * source[i] / maxSourceValue);
    }
}

Or when you want to create a new target pixel buffer, like this:

public static ushort[] ConverTo16Bit(ushort[] source, int sourceBitsPerPixel)
{
    const int maxTargetValue = (1 << 16) - 1;
    int maxSourceValue = (1 << sourceBitsPerPixel) - 1;

    return source
        .Select(value => (ushort)(maxTargetValue * value / maxSourceValue))
        .ToArray();
}