1

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!

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

How do you determine the appropriate dtype? What's the relation between QImage.format() and the dtype?
I don't recommend using an image format for which uint8 is not an appropriate dtype. numpy won't be able to do much with any of the other packed formats. Use QImage.convertToFormat() to convert the QImage to one of the RGB32 formats.
np.frombuffer(img.bits(), dtype=np.uint32).reshape(img.height(), img.width()) with qRgba, qRed etc. worked best for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.