Search⌘ K
AI Features

Numpy Integration

Explore how to integrate Pycairo with NumPy by creating arrays from image surfaces and constructing surfaces from NumPy arrays. Understand techniques for manipulating pixel data to generate complex vector graphics and write output files.

Creating a numpy array from a surface

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

Python 3.8
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 function. There is no need to convert the data to a byte buffer, because numpy understands memoryview objects.

We ...