Question

I want to create an "array_like" QImage subclass that can be passed to numpy.array(). I'd like to avoid using PIL as a substitute; the whole point of this is to avoid the dependency on PIL. Besides, constantly converting between QImage and the PIL Image is impractical for my program.

I find the documentation cryptic, and after reading it I'm still confused about how to emulate the array interface. As the numpy documentation states, to qualify as an "array_like" object, it needs the __array_interface__ attribute, which is a dictionary with five keys. However, I've never dealt with types, buffers, and memory before; if someone could explain how to solve this problem it would be much appreciated.

I'm using Python 3.3 and PySide 1.1.2. Thanks to all who reply!

Was it helpful?

Solution

It's easier to just use the buffer object returned from QImage.bits() and np.frombuffer().

def qimage2array(q_image):
    width = q_image.width()
    height = q_image.height()
    arr = np.frombuffer(q_image.bits(), dtype=np.uint8).reshape([height, width, -1])
    return arr
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top