Numpy Integration

In this lesson, we'll learn r to integrate numpy with Pycairo.

Creating a numpy array from a surface

We can create a numpy array from an ImageSurface like this:

Press + to interact
import cairo
import numpy as np
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 400, 400)
ctx = cairo.Context(surface)
ctx.set_source_rgb(1, 1, 1)
ctx.paint()
ctx.set_source_rgb(1, 0, 0)
ctx.rectangle(100, 100, 200, 200)
ctx.fill()
buffer = surface.get_data()
data = np.ndarray(shape=(400, 400), dtype=np.uint32, buffer=buffer)
print(hex(data[10, 10]))
print(hex(data[200, 200]))

We create our red square image in the same way that we did in the Pillow example. Then, we obtain the data using the get_data ...