[Numpy-discussion] PyArray_BASE equivalent in python

Nathaniel Smith njs at pobox.com
Tue Nov 26 15:03:55 EST 2013


On Tue, Nov 26, 2013 at 11:54 AM, Peter Rennert <p.rennert at cs.ucl.ac.uk> wrote:
> Hi,
>
> I as the title says, I am looking for a way to set in python the base of
> an ndarray to an object.
>
> Use case is porting qimage2ndarray to PySide where I want to do
> something like:
>
> In [1]: from PySide import QtGui
>
> In [2]: image =
> QtGui.QImage('/home/peter/code/pyTools/sandbox/images/faceDemo.jpg')
>
> In [3]: import numpy as np
>
> In [4]: a = np.frombuffer(image.bits())
>
> --> I would like to do something like:
> In [5]: a.base = image
>
> --> to avoid situations such as:
> In [6]: del image
>
> In [7]: a
> Segmentation fault (core dumped)

This is a bug in PySide -- the buffer object returned by image.bits()
needs to hold a reference to the original image. Please report a bug
to them. You will also get a segfault from code that doesn't use numpy
at all, by doing things like:

bits = image.bits()
del image
<anything involving the bits object>

As a workaround, you can write a little class with an
__array_interface__ attribute that points to the image's contents, and
then call np.asarray() on this object. The resulting array will have
your object as its .base, and then your object can hold onto whatever
references it wants.

-n



More information about the NumPy-Discussion mailing list