[Numpy-discussion] PyArray_BASE equivalent in python

Peter Rennert p.rennert at cs.ucl.ac.uk
Wed Nov 27 09:16:07 EST 2013


First, sorry for not responding to your other replies, there was a jam 
in Thunderbird and I did not receive your answers.

The bits() seem to stay alive after deleting the image:

from PySide import QtGui
image = QtGui.QImage('/home/peter/code/pyTools/sandbox/images/faceDemo.jpg')
a = image.bits()
del image
b = str(a)

Works. But it might still be a Garbage collector thing and it might 
break later. I do not know enough about Python and its buffers to know 
what to expect here.

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


Thanks all for your help,

P

On 11/26/2013 10:58 PM, Nathaniel Smith wrote:
> On Tue, Nov 26, 2013 at 2:55 PM, Peter Rennert <p.rennert at cs.ucl.ac.uk> wrote:
>> Btw, I just wanted to file a bug at PySide, but it might be alright at
>> their end, because I can do this:
>>
>> from PySide import QtGui
>>
>> image = QtGui.QImage('/home/peter/code/pyTools/sandbox/images/faceDemo.jpg')
>>
>> a = image.bits()
>>
>> del image
>>
>> a
>> #<read-write buffer ptr 0x7f5fe0034010, size 1478400 at 0x3c1a6b0>
> That just means that the buffer still has a pointer to the QImage's
> old memory. It doesn't mean that following that pointer won't crash.
> Try str(a) or something that actually touches the buffer contents...
>




More information about the NumPy-Discussion mailing list