简体   繁体   中英

How to create a uint16 numpy array from a uint8 raw image data array

When interfacing with a USB camera and grabbing image data, I am running into problems with saving the data as 16 bit. I have the camera pixel format set to Mono16, however whenever I save the raw image data to a numpy array, the array defaults to a uint8 datatype. I have noticed that the raw data array doubles in size when switching from Mono8 to Mono16. I have looked into numpy as_strided, but that still didn't fix the issues. Here is a snippet of code to help show a basic example of the situation.

>>>c.startCapture()
>>>fireSoftwareTrigger()
>>>im = c.retrieveBuffer()
>>>c.stopCapture()
>>>cols = im.getCols()
>>>cols
964
>>>rows = im.getRows()
>>>rows
724
>>>data = numpy.array(im.getData())
>>>len(data)
1395872
>>>rows*cols
697936
>>>data.dtype
dtype('uint8')

You can use view casting. Note that view casting reinterprets the data buffer without actually modifying it, so it is cheap.

data = numpy.array(im.getData()).view(numpy.uint16)

if the data's byte order matches your machine's native one.

Otherwise you'd need to use one of

data = numpy.array(im.getData()).view('<u2')
data = numpy.array(im.getData()).view('>u2')

the '>' / '<' in the dtype specification string stands for big/little endian. 'u' means unsigned int, '2' means two bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM