Home > other >  How can I extract those bits from 16bit LE data?
How can I extract those bits from 16bit LE data?

Time:05-12

I've got 16 bit data in the following LE bit format:

B4 | B5 | C1 | C2 | C3 | D1 | D2 | D3

A1 | A2 | A3 | A4 | A5 | B1 | B2 | B3

Each letter represents one data category that I want to extract and make a seperate image from.

Using this python code, I managed to create an image from the A layer, but I did not succeed in extracting B, C and D.

# using numpy and PIL
data = np.fromfile(i, dtype=np.dtype('<u2')).reshape(size, size)
A = ((data & 31) - 1).astype('uint8')
image_A = Image.fromarray(A)

Does anyone know how that would work?

Sample data (512x512), Output A

CodePudding user response:

Using a dictionary of bitmasks and some bit twiddling to compute the requisite shifts:

import numpy as np
from PIL import Image

def extract_mask(arr, mask):
    # bit twiddling magic (count trailing zeros)
    shift = int(np.log2(mask & -mask))
    return (arr & mask) >> shift

masks = {
    "A": 0b000_000_00000_11111,
    "B": 0b000_000_11111_00000,
    "C": 0b000_111_00000_00000,
    "D": 0b111_000_00000_00000,
}

filename = "512x512.buffer"
size = 512
data = np.fromfile(filename, dtype="<u2").reshape(size, size)
images = {
    k: Image.fromarray(extract_mask(data, mask).astype(np.uint8))
    for k, mask in masks.items()
}
  • Related