Debian Codegraph @

tests/test_surface_numpy.py

raw symbols SCIP
1 import os
2 import tempfile
3
4 import cairo
5 import pytest
6
7 numpy = pytest.importorskip("numpy")
8
9
10 def test_image_surface_create_for_data_numpy_array():
11 width, height = 255, 255
12 data = numpy.ndarray(shape=(height, width), dtype=numpy.uint32)
13
14 for y in range(height):
15 for x in range(width):
16 alpha = y
17 b = int(x * alpha / 255.0)
18 g = int(y * alpha / 255.0)
19 data[y][x] = (b | g << 8 | alpha << 24)
20
21 surface = cairo.ImageSurface.create_for_data(
22 data, cairo.FORMAT_ARGB32, width, height)
23
24 # for debugging
25 fd, filename = tempfile.mkstemp(prefix='pycairo_', suffix='.png')
26 os.close(fd)
27 surface.write_to_png(filename)
28 os.unlink(filename)
29
30
31 def test_image_surface_get_data_to_numpy_array():
32 w, h = 300, 128
33 surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
34 ctx = cairo.Context(surface)
35
36 ctx.set_source_rgb(1, 1, 1) # white
37 ctx.set_operator(cairo.OPERATOR_SOURCE)
38 ctx.paint()
39
40 # Draw out the triangle using absolute coordinates
41 ctx.move_to(w / 2, h / 3)
42 ctx.line_to(2 * w / 3, 2 * h / 3)
43 ctx.rel_line_to(-1 * w / 3, 0)
44 ctx.close_path()
45
46 ctx.set_source_rgb(0, 0, 0) # black
47 ctx.set_line_width(15)
48 ctx.stroke()
49
50 buf = surface.get_data()
51
52 a = numpy.ndarray(shape=(h, w), dtype=numpy.uint32, buffer=buf)
53
54 # draw a vertical blue line
55 a[:, 40] = 0xff | 0xff << 24
56
57 # for debugging
58 fd, filename = tempfile.mkstemp(prefix='pycairo_', suffix='.png')
59 os.close(fd)
60 surface.write_to_png(filename)
61 os.unlink(filename)