Python: reading 12-bit binary files

后端 未结 4 2072
情话喂你
情话喂你 2020-12-03 04:05

I am trying to read 12-bit binary files containing images (a video) using Python 3.

To read a similar file but encoded in 16 bits, the following works very well:

4条回答
  •  借酒劲吻你
    2020-12-03 04:45

    Here's yet another variation. My data format is:

    first uint12: most significant 4 bits from least significant 4 bits of second uint8 + least significant 8 bits from first uint8

    second uint12: most significant 8 bits from third uint8 + least significant 4 bits from most significant 4 bits from second uint8

    The corresponding code is:

    def read_uint12(data_chunk):
        data = np.frombuffer(data_chunk, dtype=np.uint8)
        fst_uint8, mid_uint8, lst_uint8 = numpy.reshape(data, (data.shape[0] // 3, 3)).astype(numpy.uint16).T
        fst_uint12 = ((mid_uint8 & 0x0F) << 8) | fst_uint8
        snd_uint12 = (lst_uint8 << 4) | ((mid_uint8 & 0xF0) >> 4)
        return numpy.reshape(numpy.concatenate((fst_uint12[:, None], snd_uint12[:, None]), axis=1), 2 * fst_uint12.shape[0])
    

提交回复
热议问题