2

In Python2.7, from an USB bulk transfer I get an image frame from a camera:

frame = dev.read(0x81, 0x2B6B0, 1000)

I know that one frame is 342x260 = 88920 pixels little endian, because that I read 2x88920 = 177840 (0x2B6B0) from the bulk transfer.

How can I convert the content of the frame array that is typecode=B into an uint16 big endian array?

Paul G.
  • 461
  • 6
  • 21

1 Answers1

1

Something like this should do the trick:

frame_short_swapped = array.array('H', ((j << 8) | i
                                        for (i,j)
                                        in zip(frame[::2], frame[1::2])))

It pairs two consecutive bytes from frame and unpacks that pair into i and j. Shift j one byte left and or it with i, effectively swap bytes (aka endianness conversion for 2 byte type) and feed that into an H type array. I am a bit uneasy about that bit, since it should correspond to C short type (according to docs), but type sizes really only guarantee minimal length. I guess you would need to introduce ctypes.c_uint16 if strict about that?

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
  • nice, that seems to work, a little test with x = [3,103,3,103] converted it to array('H', [26371, 26371]), which was what I looking for. I will test it soon with my camera data. Sorry my english is bad but by your last sentence you mean I should use ctypes.c_uint16 for frame_short_swapped? Could I also use a numpy.uint16 array? – Paul G. Jun 26 '18 at 17:03
  • I just meant that if you strictly require`uint16`, typecode `H` (or `short`) does not guarantee that. If you rely on that / it was a problem, you would have to go one step further and use something else to handle and store your values. Like `ctypes` or, yes, `numpy`. – Ondrej K. Jun 26 '18 at 17:11
  • 1
    Oh, sorry, I should have probably added. It's not guaranteed that `short` is (only) 2 bytes long, but it actually is very likely and chances are on most system you encounter it is. :) In other words, depending on your use case, keep that in mind, but perhaps no action required (at least for now). – Ondrej K. Jun 26 '18 at 17:36