On Wed, Nov 27, 2013 at 2:16 PM, Peter Rennert <p.rennert@cs.ucl.ac.uk> wrote:
As a solution I have done something similar as it was proposed earlier, just that I derived from ndarray and kept the QImage reference it it:
from PySide import QtGui as _qt import numpy as _np
class MemoryTie(np.ndarray): def __new__(cls, image): # Retrieving parameters for _np.ndarray() dims = [image.height(), image.width()]
strides = [[] for i in range(2)] strides[0] = image.bytesPerLine()
bits = image.bits()
if image.format() == _qt.QImage.Format_Indexed8: dtype = _np.uint8 strides[1] = 1 elif image.format() == _qt.QImage.Format_RGB32 \ or image.format() == _qt.QImage.Format_ARGB32 \ or image.format() == _qt.QImage.Format_ARGB32_Premultiplied: dtype = _np.uint32 strides[1] = 4 elif image.format() == _qt.QImage.Format_Invalid: raise ValueError("qimageview got invalid QImage") else: raise ValueError("qimageview can only handle 8- or 32-bit QImages")
# creation of ndarray obj = _np.ndarray(dims, _np.uint32, bits, 0, strides, 'C').view(cls) obj._image = image
return obj
Don't do that. Use my recipe. You don't really want your RGBA tuples interpreted as uint32s, do you? from PySide import QtGui import numpy as np class QImageArray(object): def __init__(self, qimage): shape = (qimage.height(), qimage.width(), -1) # Generate an ndarray from the image bits and steal its # __array_interface__ information. arr = np.frombuffer(qimage.bits(), dtype=np.uint8).reshape(shape) self.__array_interface__ = arr.__array_interface__ # Keep the QImage alive. self.qimage = qimage def qimage2ndarray(qimage): return np.asarray(QImageArray(qimage)) qimage = QtGui.QImage('/Users/rkern/git/scipy/scipy/misc/tests/data/icon.png') arr = qimage2ndarray(qimage) del qimage print arr -- Robert Kern