Exemplo n.º 1
0
    def __init__(self, size, *args, **kwargs):
        super().__init__()
        self._width = size[0]
        self._height = size[1]
        self.pix_format = kwargs.get('pix_format', 'bgra32')

        shape = (self._height, self._width, 4)
        buffer = np.zeros(shape, dtype=np.uint8)
        canvas_klass = pix_format_canvases[self.pix_format]
        self.gc = canvas_klass(buffer, bottom_up=True)
        self.marker_gc = MarkerRenderer(
            buffer, pix_format=self.pix_format, bottom_up=True
        )

        # init the state variables
        clip = agg.Rect(0, 0, self._width, self._height)
        self.canvas_state = agg.GraphicsState(clip_box=clip)
        self.stroke_paint = agg.SolidPaint(0.0, 0.0, 0.0)
        self.fill_paint = agg.SolidPaint(0.0, 0.0, 0.0)
        self.path = CompiledPath()
        self.text_transform = agg.Transform()
        self.text_pos = (0.0, 0.0)
        self.transform = agg.Transform()
        self.font = None
        self.__state_stack = []

        # For HiDPI support
        self.base_scale = kwargs.pop('base_pixel_scale', 1)
        self.transform.scale(self.base_scale, self.base_scale)

        # Make this look like a kiva.agg GC
        self.bmp_array = buffer
Exemplo n.º 2
0
def test_bad_method_args():
    canvas = agg.CanvasG8(np.zeros((1, 1), dtype=np.uint8))
    pix_format = agg.PixelFormat.Gray8
    gs = agg.GraphicsState()
    path = agg.Path()
    transform = agg.Transform()

    with pytest.raises(TypeError):
        canvas.draw_image(None, pix_format, transform, gs)
    with pytest.raises(TypeError):
        canvas.draw_image(canvas.array, None, transform, gs)
    with pytest.raises(TypeError):
        canvas.draw_image(canvas.array, pix_format, None, gs)
    with pytest.raises(TypeError):
        canvas.draw_image(canvas.array, pix_format, transform, None)
    # But this version should work
    canvas.draw_image(canvas.image, None, transform, gs)

    with pytest.raises(TypeError):
        canvas.draw_shape(None, transform, gs)
    with pytest.raises(TypeError):
        canvas.draw_shape(path, None, gs)
    with pytest.raises(TypeError):
        canvas.draw_shape(path, transform, None)

    text = "Hello!"
    font = agg.Font("Times New Roman", 12.0, agg.FontCacheType.RasterFontCache)
    with pytest.raises(TypeError):
        canvas.draw_text(text, None, transform, gs)
    with pytest.raises(TypeError):
        canvas.draw_text(text, font, None, gs)
    with pytest.raises(TypeError):
        canvas.draw_text(text, font, transform, None)
Exemplo n.º 3
0
def spiral(size, hue, sat, val):
    canvas = agg.CanvasRGB24(np.zeros((size[1], size[0], 3), dtype=np.uint8))
    gs = agg.GraphicsState(drawing_mode=agg.DrawingMode.DrawFill)
    transform = agg.Transform()
    circle = agg.Path()
    circle.ellipse(0, 0, CIRCLE_SIZE, CIRCLE_SIZE)

    divisions = np.linspace(0, 2*np.pi, CIRCLE_COUNT, endpoint=False)
    centers = np.stack((np.cos(divisions), np.sin(divisions)), axis=1)
    offsets = compute_offsets(np.sqrt(size[0]**2 + size[1]**2) / 2)
    color_count = len(offsets)

    hsv = np.ones((color_count, 1, 3))
    hsv[:, 0, 0] = np.linspace(hue[0], hue[1], color_count, endpoint=False)
    hsv[:, 0, 1] = np.linspace(sat[0], sat[1], color_count, endpoint=False)
    hsv[:, 0, 2] = np.linspace(val[0], val[1], color_count, endpoint=False)
    spectrum = hsv2rgb(hsv).reshape(color_count, 3)

    for idx, offset in enumerate(offsets):
        paint = agg.SolidPaint(*spectrum[idx])
        radius = np.pi * offset / CIRCLE_COUNT
        scale = radius / CIRCLE_SIZE
        for i in range(CIRCLE_COUNT):
            if ((idx + i) % 2) == 0:
                continue
            transform.reset()
            transform.translate(size[0]/2 + offset*centers[i, 0],
                                size[1]/2 + offset*centers[i, 1])
            transform.scale(scale, scale)
            canvas.draw_shape(circle, transform, gs, fill=paint)

    imsave('spiral.png', canvas.array)
Exemplo n.º 4
0
Arquivo: draw.py Projeto: zplab/zplib
def draw_mask(image_shape, geometry, antialias=False):
    """Draw a mask (0-255) from a given celiagg path. Requires celiagg installed.

    Note: to produce a True/False mask from the output, simply do the following:
        mask = draw_mask(image_shape, geometry)
        bool_mask = mask > 0

    Parameters:
        image_shape: shape of the resulting image
        geometry: celiagg VertexSource class, such as celiagg.Path or
            celiagg.BSpline, containing geometry to draw
        antialias: if False (default), output contains only 0 and 255. If True,
            output will be antialiased (better for visualization).

    Returns: mask array of dtype numpy.uint8
    """
    import celiagg
    image = numpy.zeros(image_shape, dtype=numpy.uint8, order='F')
    # NB celiagg uses (h, w) C-order convention for image shapes, so give it the transpose
    canvas = celiagg.CanvasG8(image.T)
    state = celiagg.GraphicsState(drawing_mode=celiagg.DrawingMode.DrawFill, anti_aliased=antialias)
    fill = celiagg.SolidPaint(1,1,1)
    transform = celiagg.Transform()
    canvas.draw_shape(geometry, transform, state, fill=fill)
    return image
Exemplo n.º 5
0
def test_stencil_size_mismatch():
    canvas = agg.CanvasRGB24(np.zeros((4, 5, 3), dtype=np.uint8))
    stencil_canvas = agg.CanvasG8(np.zeros((1, 2), dtype=np.uint8))
    gs = agg.GraphicsState(stencil=stencil_canvas.image)
    path = agg.Path()
    transform = agg.Transform()

    with pytest.raises(agg.AggError):
        canvas.draw_shape(path, transform, gs)
Exemplo n.º 6
0
def terrain(size):
    canvas = agg.CanvasRGB24(np.empty((size[1], size[0], 3), dtype='uint8'),
                             bottom_up=True)
    gs = agg.GraphicsState(drawing_mode=agg.DrawingMode.DrawFill)

    sky(size[0], size[1], canvas, gs)
    xs, ys = gen_horizon(nearest_pow2(size[0] // 4) + 1, size[0], size[1])
    draw_horizon(xs, ys / 2, canvas, gs)

    imsave('terrain.png', canvas.array)
Exemplo n.º 7
0
def test_no_text_draw_text_failure():
    if agg.HAS_TEXT:
        return

    buffer = np.zeros((1, 1), dtype=np.uint8)
    canvas = agg.CanvasG8(buffer)
    transform = agg.Transform()
    line_paint = agg.SolidPaint(1.0, 1.0, 1.0)
    gs = agg.GraphicsState()

    with pytest.raises(RuntimeError):
        canvas.draw_text("", None, transform, line_paint, line_paint, gs)
Exemplo n.º 8
0
    def _clip_impl(self, shape, drawing_mode):
        """ Internal implementation for the complex clipping methods.
        """
        size = (self._height, self._width)
        stencil = agg.CanvasG8(np.empty(size, dtype=np.uint8), bottom_up=True)
        stencil.clear(0.0, 0.0, 0.0)

        clip_box = agg.Rect(0, 0, self._width, self._height)
        gs = agg.GraphicsState(drawing_mode=drawing_mode, clip_box=clip_box)
        paint = agg.SolidPaint(1.0, 1.0, 1.0)
        stencil.draw_shape(shape, self.transform, gs, stroke=paint, fill=paint)

        self.canvas_state.stencil = stencil.image
Exemplo n.º 9
0
    def __init__(self, size, *args, **kwargs):
        super(GraphicsContext, self).__init__()
        self._width = size[0]
        self._height = size[1]
        self.pix_format = kwargs.get('pix_format', 'rgba32')

        shape = (self._height, self._width, 4)
        canvas_klass = pix_format_canvases[self.pix_format]
        self.gc = canvas_klass(np.zeros(shape, dtype=np.uint8), bottom_up=True)

        # init the state variables
        clip = agg.Rect(0, 0, self._width, self._height)
        self.canvas_state = agg.GraphicsState(clip_box=clip)
        self.stroke_paint = agg.SolidPaint(0.0, 0.0, 0.0)
        self.fill_paint = agg.SolidPaint(0.0, 0.0, 0.0)
        self.path = CompiledPath()
        self.text_transform = agg.Transform()
        self.text_pos = (0.0, 0.0)
        self.transform = agg.Transform()
        self.font = None
        self.__state_stack = []
Exemplo n.º 10
0
def interpret_state(style, stroke, fill):
    state = agg.GraphicsState(
        master_alpha=float(style.get('opacity', 1.0)),
        line_width=parse_united(style.get('stroke-width', '1')),
        miter_limit=float(style.get('stroke-miterlimit', 4.0)))

    mode = agg.DrawingMode.DrawFillStroke
    if 'nonzero' == style.get('stroke-fillrule', 'nonzero'):
        if stroke is None and fill is not None:
            mode = agg.DrawingMode.DrawFill
        elif stroke is not None and fill is None:
            mode = agg.DrawingMode.DrawStroke
        elif stroke is not None and fill is not None:
            mode = agg.DrawingMode.DrawFillStroke
    else:
        if stroke is None and fill is not None:
            mode = agg.DrawingMode.EofDrawFill
        elif stroke is not None and fill is None:
            mode = agg.DrawingMode.EofDrawStroke
        elif stroke is not None and fill is not None:
            mode = agg.DrawingMode.EofDrawFillStroke
    state.drawing_mode = mode

    return state
Exemplo n.º 11
0
def state():
    return agg.GraphicsState(anti_aliased=False, line_width=1.0)
Exemplo n.º 12
0
star_shape = agg.Path()
star_shape.lines([pts[i] for i in (0, 2, 4, 1, 3)])
star_shape.close()
star_transform = agg.Transform()
star_transform.translate(SIZE / 2, SIZE / 2)
star_transform.rotate(-np.pi / 2)
star_transform.translate(-SIZE / 2, -SIZE / 2)

big_box = agg.Path()
big_box.rect(0, 0, SIZE, SIZE)
small_box = agg.Path()
small_box.rect(0, 0, SIZE / 2, SIZE / 2)

stencil_canvas = agg.CanvasG8(np.zeros((SIZE, SIZE), dtype=np.uint8))
canvas = agg.CanvasRGB24(np.zeros((SIZE, SIZE, 3), dtype=np.uint8))
gs = agg.GraphicsState(drawing_mode=agg.DrawingMode.DrawFill, line_width=6.0)
transform = agg.Transform()
blue_paint = agg.SolidPaint(0.1, 0.1, 1.0)
white_paint = agg.SolidPaint(1.0, 1.0, 1.0)
stops = ((0.0, 0.0, 0.0, 0.0, 1.0), (1.0, 0.3, 0.3, 0.75, 1.0))
bw_grad = agg.LinearGradientPaint(0, 0, 2, 5, stops,
                                  agg.GradientSpread.SpreadReflect,
                                  agg.GradientUnits.UserSpace)
stops = ((0.0, 1.0, 1.0, 1.0, 1.0), (1.0, 0.7, 0.7, 0.25, 1.0))
lin_grad = agg.LinearGradientPaint(0, 0, 2, 5, stops,
                                   agg.GradientSpread.SpreadReflect,
                                   agg.GradientUnits.UserSpace)

stencil_canvas.clear(0, 0, 0)
stencil_canvas.draw_shape(star_shape, star_transform, gs, fill=white_paint)
Exemplo n.º 13
0
import celiagg as agg
import numpy as np
from skimage.io import imsave

canvas = agg.CanvasRGB24(np.ones((400, 400, 3), dtype=np.uint8))
state = agg.GraphicsState(drawing_mode=agg.DrawingMode.DrawStroke,
                          line_width=10.0)
transform = agg.Transform()
red_paint = agg.SolidPaint(1.0, 0.0, 0.0)
black_paint = agg.SolidPaint(0.0, 0.0, 0.0)
font = agg.Font("/Library/Fonts/Verdana.ttf", 96.0,
                agg.FontCacheType.RasterFontCache)
path = agg.Path()
path.ellipse(200, 200, 190, 190)
canvas.clear(1.0, 1.0, 1.0)
canvas.draw_shape(path, transform, state, stroke=red_paint)
transform.translate(30.0, 220.0)
canvas.draw_text("celiagg", font, transform, state, stroke=black_paint)

imsave("example.png", canvas.array)
Exemplo n.º 14
0
import pathlib
import pickle
import numpy

import celiagg
import freeimage
from zplib.curve import spline_geometry
from zplib.curve import interpolate
from zplib.image import resample

AGG_STATE = celiagg.GraphicsState(anti_aliased=False)
AGG_PAINT = celiagg.SolidPaint(1, 1, 1)
AGG_TRANSFORM = celiagg.Transform()
AGG_TRANSPARENT = celiagg.SolidPaint(0, 0, 0, 0)


def write_xy_positions(filename, positions):
    position_lines = ['{}\t{}'.format(x, y) for x, y in positions]
    with open(filename, 'w') as f:
        f.write('\n'.join(position_lines))


def save_centerline(metadata, centerline_file):
    spine_tck = metadata['spine_tck']
    positions = interpolate.spline_interpolate(spine_tck, 50)
    write_xy_positions(centerline_file, positions)


def save_landmarks(metadata, landmark_file):
    spine_tck = metadata['spine_tck']
    vulva_t = metadata['vulva_t']