question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Example writing onto existing numpy buffer dies

See original GitHub issue

We can confirm the problem raised by stuaxo on Feb 19, 2015. Running the same code with numpy 1.11.1 and 1.9.1 gives the same error with cairocffi. However, if we switch to the cffi-from-buffer branch it gives another error.

Output from cairocffi (branch cffi-from-buffer):

ValueError                                Traceback (most recent call last)
/home/a000680/dev/cairocffi_example.py in <module>()
     32 data = numpy.zeros((width, height, 4), dtype=numpy.uint8)
     33 surface = cairo.ImageSurface.create_for_data(
---> 34     data, cairo.FORMAT_ARGB32, width, height)
     35 cr = cairo.Context(surface)
     36 

/home/a000680/usr/src/cairocffi/cairocffi/surfaces.py in create_for_data(cls, data, format, width, height, stride)
    665 
    666         """
--> 667         return cls(format, width, height, data, stride)
    668 
    669     @staticmethod

/home/a000680/usr/src/cairocffi/cairocffi/surfaces.py in __init__(self, format, width, height, data, stride)
    657             pointer = cairo.cairo_image_surface_create_for_data(
    658                 ffi.cast('char*', address), format, width, height, stride)
--> 659         Surface.__init__(self, pointer, target_keep_alive=data)
    660 
    661     @classmethod

/home/a000680/usr/src/cairocffi/cairocffi/surfaces.py in __init__(self, pointer, target_keep_alive)
    138         self._pointer = ffi.gc(pointer, cairo.cairo_surface_destroy)
    139         self._check_status()
--> 140         if target_keep_alive not in (None, ffi.NULL):
    141             keep_alive = KeepAlive(target_keep_alive)
    142             _check_status(cairo.cairo_surface_set_user_data(

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

If you on line 140 change to the following:

        import numpy as np
        if np.all(target_keep_alive) not in (None, ffi.NULL):

The code seems to run correctly.

Alternatively we saw that we could get the example to run also with the master branch provided you flatten the data (data.ravel() instead of data as the first argument to create_for_data()) and do the following fix in surface.py in the ImageSurface class:

    def __init__(self, format, width, height, data=None, stride=None, tka=True):
        if data is None:
            pointer = cairo.cairo_image_surface_create(format, width, height)
        else:
            if stride is None:
                stride = self.format_stride_for_width(format, width)
            address, length = from_buffer(data)
            if length < stride * height:
                raise ValueError('Got a %d bytes buffer, needs at least %d.'
                                 % (length, stride * height))
            pointer = cairo.cairo_image_surface_create_for_data(
                ffi.cast('char*', address), format, width, height, stride)
        Surface.__init__(self, pointer, target_keep_alive=tka)

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
xy-23commented, Mar 18, 2020

I change this:

return obj.array_interface[‘data’][0], sum(obj,shape)

into this: return ctypes.addressof(ctypes.c_char.from_buffer(obj)), reduce(lambda x, y: x*y , obj.shape)

and change this:

    def __init__(self, pointer, target_keep_alive=None):
        self._pointer = ffi.gc(
            pointer, _keepref(cairo, cairo.cairo_surface_destroy))
        self._check_status()
        if target_keep_alive not in (None, ffi.NULL):
            keep_alive = KeepAlive(target_keep_alive)
            _check_status(cairo.cairo_surface_set_user_data(
                self._pointer, SURFACE_TARGET_KEY, *keep_alive.closure))
            keep_alive.save()

into this: (add .any())

    def __init__(self, pointer, target_keep_alive=None):
        self._pointer = ffi.gc(
            pointer, _keepref(cairo, cairo.cairo_surface_destroy))
        self._check_status()
        if target_keep_alive.any() not in (None, ffi.NULL):
            keep_alive = KeepAlive(target_keep_alive)
            _check_status(cairo.cairo_surface_set_user_data(
                self._pointer, SURFACE_TARGET_KEY, *keep_alive.closure))
            keep_alive.save()

and it works successfully. btw, don’t forget from functools import reduce

0reactions
liZecommented, Apr 12, 2020

Closed by #152.

Read more comments on GitHub >

github_iconTop Results From Across the Web

simple example writing onto existing numpy buffer dies #51
This example of dies - http://stackoverflow.com/questions/10031580/how-to-write-simple-geometric-shapes-into-numpy-arrays/10031877#10031877 ...
Read more >
fastest method to dump numpy array into string - Stack Overflow
I know that numpy allows to get buffer numpy.getbuffer, but it isn't obvious to me, how to use this dumped buffer to obtaine...
Read more >
From Python to Numpy - LaBRI
An open-source book about numpy vectorization techniques, based on experience, practice and descriptive examples.
Read more >
Reading and Writing Files in Python - PythonForBeginners.com
In this tutorial, learn about reading and writing to files using the python read and write methods. - PythonForBeginners.com.
Read more >
Memoryview Benchmarks - Pythonic Perambulations
It has to do with memoryviews, a new way of working with memory buffers in cython. I've been thinking recently about how to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found