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
def sky(width, height, canvas, gs): def rcolor(): return hsv2rgb(.55 + randneghalf2half() * .25, .6 + randneghalf2half() * .125, .25 + randneghalf2half() * .125) transform = agg.Transform() starpaint = agg.SolidPaint(*hsv2rgb(.165, .96, .99)) starshape = agg.Path() angles = np.linspace(0, 2 * np.pi, num=5, endpoint=False) pts = np.stack([np.cos(angles), np.sin(angles)]).T * 7 starshape.lines([pts[i] for i in (0, 2, 4, 1, 3)]) starshape.close() bgshape = agg.Path() bgshape.rect(0, 0, width, height) bgpaint = agg.LinearGradientPaint(0, 0, 0, height, randgradstops(2, rcolor), agg.GradientSpread.SpreadReflect, agg.GradientUnits.UserSpace) canvas.draw_shape(bgshape, transform, gs, fill=bgpaint) star_count = 40 xs = np.random.rand(star_count) * width ys = np.random.rand(star_count) * height for x, y in zip(xs, ys): transform.reset() transform.translate(x, y) canvas.draw_shape(starshape, transform, gs, fill=starpaint)
def interpret_color(value, context): color = parse_color(value) if color is not None: return agg.SolidPaint(*color) elif value.lower() == 'none': return None elif value.startswith('url'): match = re.match(r'url\(#(?P<label>\w+)\)', value) if match is None: return None obj = context.get(match.group('label')) if obj is None or 'type' not in obj: return None if obj['type'] == 'linearGradient': grad = agg.LinearGradientPaint( obj['x1'], obj['y1'], obj['x2'], obj['y2'], obj['stops'], obj.get('spreadMethod', agg.GradientSpread.SpreadPad), obj.get('gradientUnits', agg.GradientUnits.ObjectBoundingBox)) grad.transform = obj.get('gradientTransform', agg.Transform()) return grad if obj['type'] == 'radialGradient': grad = agg.RadialGradientPaint( obj['cx'], obj['cy'], obj['r'], obj['fx'], obj['fy'], obj['stops'], obj.get('spreadMethod', agg.GradientSpread.SpreadPad), obj.get('gradientUnits', agg.GradientUnits.ObjectBoundingBox)) grad.transform = obj.get('gradientTransform', agg.Transform()) return grad
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)
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
def clear_rect(self, rect): shape = agg.Path() shape.rect(*rect) paint = agg.SolidPaint(0.0, 0.0, 0.0, 0.0) self.canvas_state.drawing_mode = agg.DrawingMode.DrawFill self.gc.draw_shape( shape, self.transform, self.canvas_state, fill=paint )
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 = []
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)
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
def set_stroke_color(self, color): self.stroke_paint = agg.SolidPaint(*color)
def set_fill_color(self, color): self.fill_paint = agg.SolidPaint(*color)
def paint(): return agg.SolidPaint(1 / 255, 1 / 255, 1 / 255)
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) canvas.clear(1, 1, 1) canvas.draw_shape(big_box, transform, gs, fill=bw_grad)
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)
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']