コード例 #1
0
    def _setup_cairo(self, w, h):
        self.w = w
        self.h = h
        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
        self.ctx = cairo.Context(self.surface)
        self.ctx.set_antialias(cairo.ANTIALIAS_GOOD)

        self.ctx.scale(w, h)
コード例 #2
0
 def __init__(self, IMAGE_SIZE):
     """ """
     self.IMAGE_SIZE = [IMAGE_SIZE] * 2
     # Prepare cairo surface
     self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                       self.IMAGE_SIZE[0],
                                       self.IMAGE_SIZE[1])
     self.cr = cairo.Context(self.surface)
コード例 #3
0
 def __init__(self, width, height, bg_color=None):
     """"Initialize."""
     self.width = width
     self.height = height
     self._cairo_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width,
                                              height)
     if bg_color:
         rectangle(2 * width, 2 * height, fill=bg_color).draw(self)
コード例 #4
0
 def _get_printed_image_surface(self):
     width, height = self.get_width_height()
     renderer = RendererCairo(self.figure.dpi)
     renderer.set_width_height(width, height)
     surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
     renderer.set_ctx_from_surface(surface)
     self.figure.draw(renderer)
     return surface
コード例 #5
0
def paint_text(text, max_word=None, font_size=28, color_noise=(0.,0.6), random_shift=True, font_list=FONT_LIST):
    '''
    Text가 그려진 이미지를 만드는 함수
    '''
    if max_word is None:
        # None이면, text의 word 갯수에 맞춰서 생성
        max_word = len(text)
    h = font_size + 12  # 이미지 높이, font_size + padding
    w = font_size * (1 + max_word) + 12  # 이미지 폭

    surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)
    with cairo.Context(surface) as context:
        context.set_source_rgb(1, 1, 1)  # White
        context.paint()

        # Font Style : Random Pick
        context.select_font_face(
                np.random.choice(font_list),
                cairo.FONT_SLANT_NORMAL,
                np.random.choice([cairo.FONT_WEIGHT_BOLD,
                                  cairo.FONT_WEIGHT_NORMAL]))

        context.set_font_size(font_size)
        box = context.text_extents(text)
        border_w_h = (4, 4)
        if box[2] > (w - 2 * border_w_h[1]) or box[3] > (h - 2 * border_w_h[0]):
            raise IOError(('Could not fit string into image.'
                           'Max char count is too large for given image width.'))

        # Random Shift을 통해, 이미지 Augmentation
        max_shift_x = w - box[2] - border_w_h[0]
        max_shift_y = h - box[3] - border_w_h[1]

        if random_shift:
            top_left_x = np.random.randint(0, int(max_shift_x))
            top_left_y = np.random.randint(0, int(max_shift_y))
        else:
            top_left_x = np.random.randint(3, 10) # Default padding
            top_left_y = int(max_shift_y)//2 # Default position = center in heights

        context.move_to(top_left_x - int(box[0]),
                        top_left_y - int(box[1]))

        # Draw Text
        rgb = np.random.uniform(*color_noise, size=3)

        context.set_source_rgb(*rgb)
        context.show_text(text)

    # cairo data format to numpy data format
    buf = surface.get_data()
    text_image = np.frombuffer(buf, np.uint8)
    text_image = text_image.reshape(h, w, 4)
    text_image = text_image[:, :, :3]
    text_image = text_image.astype(np.float32) / 255

    return text_image
コード例 #6
0
ファイル: tracepath.py プロジェクト: mobeets/tracepath_spline
 def __init_cairo(self):
     sur = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.n, self.n)
     ctx = cairo.Context(sur)
     ctx.scale(self.n, self.n)
     self.sur = sur
     self.ctx = ctx
     self.clear_canvas()
     self.__get_colors(COLOR_PATH)
     self.n_colors = len(self.colors)
コード例 #7
0
ファイル: renderCairo.py プロジェクト: vaibhavkarve/kaprekar
    def initpicture(self,imagedim,backcolor):
        self.mimagedim = imagedim
        self.msurface  = cairo.ImageSurface (cairo.FORMAT_ARGB32, imagedim.width(), imagedim.height())
        self.mctx      = cairo.Context(self.msurface)

        # set background
        self.mctx.rectangle(0.0, 0.0, imagedim.width(), imagedim.height())
	self.mctx.set_source_rgb(backcolor.r(), backcolor.g(), backcolor.b())
	self.mctx.fill()
コード例 #8
0
def main():
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
    ctx = cairo.Context(surface)
    ctx.set_line_cap(cairo.LINE_CAP_ROUND)
    ctx.set_line_join(cairo.LINE_JOIN_ROUND)
    ctx.set_source_rgb(1, 1, 1)
    ctx.paint()
    fractal_tree(ctx, ITERATIONS, ROOT, TRUNK_LEN, RATIO, THETA, ANGLE, PERTURB)
    surface.write_to_png("random_fractal_tree.png")
コード例 #9
0
    def __init__(self, filename, entity, options):
        self.color = (0, 0, 0)
        self.factor = 1
        self.background_color = (0, 0, 0)
        self.analyse_options(options)

        self.surface = cairo.SVGSurface(filename, 10, 10)
        self.context = cairo.Context(self.surface)

        self.factor = 1
        self.height = self.compute_height(entity)
        self.width = self.compute_width(entity)
        self.line_length = default_line_length

        self.surface = cairo.PDFSurface(
            filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2)

        self.context = cairo.Context(self.surface)
        self.compute_wire_length(entity)

        if options.format.lower() == "svg":
            self.factor = 1
            self.surface = cairo.SVGSurface(
                filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2)

        if options.format.lower() == "pdf":
            self.factor = 1
            self.surface = cairo.PDFSurface(
                filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2)

        if options.format.lower() == "ps":
            self.factor = 1
            self.surface = cairo.PSSurface(
                filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2)

        if options.format.lower() == "png":
            self.factor = float(
                options.width / (self.width + self.factor * self.line_length * 2 + self.factor * bbox_w_margin * 2))

            stride = cairo.ImageSurface.format_stride_for_width(
                cairo.FORMAT_ARGB32, 10000)
            data = bytearray(stride * 10000)
            # stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32, int(self.width)+1)
            # data = bytearray(stride * int(self.height))

            self.surface = cairo.ImageSurface(
                cairo.FORMAT_ARGB32,
                int(self.factor * self.width + self.factor *
                    self.line_length * 2 + self.factor * bbox_w_margin * 2),
                int(self.factor * self.height + self.factor * bbox_h_margin * 2), data, stride)

        self.context = cairo.Context(self.surface)
        self.draw_background(self.context)
        self.draw_entity(entity)

        self.surface.write_to_png(options.filename)
コード例 #10
0
def paint_text(text, w, h, rotate=False, ud=False, multi_fonts=False):
    global counter
    surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)
    with cairo.Context(surface) as context:
        context.set_source_rgb(1, 1, 1)  # White
        context.paint()
        # this font list works in Centos 7
        if multi_fonts:
            fonts = [
                'Century Schoolbook', 'Courier', 'STIX', 'URW Chancery L',
                'FreeMono'
            ]
            context.select_font_face(
                np.random.choice(fonts), cairo.FONT_SLANT_NORMAL,
                np.random.choice(
                    [cairo.FONT_WEIGHT_BOLD, cairo.FONT_WEIGHT_NORMAL]))
        else:
            context.select_font_face('Courier', cairo.FONT_SLANT_NORMAL,
                                     cairo.FONT_WEIGHT_BOLD)
        context.set_font_size(25)
        box = context.text_extents(text)
        border_w_h = (4, 4)
        if box[2] > (w - 2 * border_w_h[1]) or box[3] > (h -
                                                         2 * border_w_h[0]):
            raise IOError(
                'Could not fit string into image. Max char count is too large for given image width.'
            )

        # teach the RNN translational invariance by
        # fitting text box randomly on canvas, with some room to rotate
        max_shift_x = w - box[2] - border_w_h[0]
        max_shift_y = h - box[3] - border_w_h[1]
        top_left_x = np.random.randint(0, int(max_shift_x))
        if ud:
            top_left_y = np.random.randint(0, int(max_shift_y))
        else:
            top_left_y = h // 2
        context.move_to(top_left_x - int(box[0]), top_left_y - int(box[1]))
        context.set_source_rgb(0, 0, 0)
        context.show_text(text)

    buf = surface.get_data()
    a = np.frombuffer(buf, np.uint8)
    a.shape = (h, w, 4)
    a = a[:, :, 0]  # grab single channel
    a = a.astype(np.float32) / 255
    a = np.expand_dims(a, 0)
    if rotate:
        a = image.random_rotation(a, 3 * (w - top_left_x) / w + 1)
    a = speckle(a)
    #To save the test/train images
    # counter += 1
    # img = array_to_img(a, 'channels_first', scale=True)
    # fname = '{prefix}_{index}.{format}'.format(prefix='img',index=counter,format='png')
    # img.save(os.path.join('data', fname))
    return a
コード例 #11
0
    def __init__(self,
                 image=None,  # PIL image
                 size=None,
                 ctx=None,
                 imageType=None,  # determines file type
                 fileName=None,  # if set determines output file name
                 ):
        """
        Canvas can be used in four modes:
        1) using the supplied PIL image
        2) using the supplied cairo context ctx
        3) writing to a file fileName with image type imageType
        4) creating a cairo surface and context within the constructor
        """
        self.image = None
        self.imageType = imageType
        if image is not None:
            try:
                imgd = getattr(image, 'tobytes', image.tostring)("raw", "BGRA")
            except SystemError:
                r, g, b, a = image.split()
                mrg = Image.merge("RGBA", (b, g, r, a))
                imgd = getattr(mrg, 'tobytes', mrg.tostring)("raw", "RGBA")

            a = array.array('B', imgd)
            stride = image.size[0] * 4
            surface = cairo.ImageSurface.create_for_data(a, cairo.FORMAT_ARGB32, image.size[0],
                                                         image.size[1], stride)
            ctx = cairo.Context(surface)
            size = image.size[0], image.size[1]
            self.image = image
        elif ctx is None and size is not None:
            if hasattr(cairo, "PDFSurface") and imageType == "pdf":
                surface = cairo.PDFSurface(fileName, size[0], size[1])
            elif hasattr(cairo, "SVGSurface") and imageType == "svg":
                surface = cairo.SVGSurface(fileName, size[0], size[1])
            elif hasattr(cairo, "PSSurface") and imageType == "ps":
                surface = cairo.PSSurface(fileName, size[0], size[1])
            elif imageType == "png":
                surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size[0], size[1])
            else:
                raise ValueError("Unrecognized file type. Valid choices are pdf, svg, ps, and png")
            ctx = cairo.Context(surface)
            ctx.set_source_rgb(1, 1, 1)
            ctx.paint()
        else:
            surface = ctx.get_target()
            if size is None:
                try:
                    size = surface.get_width(), surface.get_height()
                except AttributeError:
                    size = None
        self.ctx = ctx
        self.size = size
        self.surface = surface
        self.fileName = fileName
コード例 #12
0
def make_text(text,
              img_shape,
              font_size,
              txt_points=None,
              font='cmbtt10',
              bold=False):
    """
    Renders text onto an image. 
    :param text: str text to put on image
    :param img_shape: tupple of image shape (w,h)
    :param font_size: int
    :param txt_points: tupple use if want to specify placement of text. Else, is random
    :param font: str 
    :param bold: bool if bold text or no
    :return: ndarray
    """
    h, w = img_shape
    surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)
    with cairo.Context(surface) as context:
        # Set background White
        context.set_source_rgb(1, 1, 1)
        context.paint()
        # set font properties
        if bold:
            context.select_font_face(font, cairo.FONT_SLANT_NORMAL,
                                     cairo.FONT_WEIGHT_BOLD)
        else:
            context.select_font_face(font, cairo.FONT_SLANT_NORMAL,
                                     cairo.FONT_WEIGHT_NORMAL)
        context.set_font_size(font_size)
        # see if text is in box
        box = context.text_extents(text)
        border_w_h = (4, 4)
        img_in_box = (box[2] > (w - 2 * border_w_h[0]) or box[3] >
                      (h - 2 * border_w_h[1])) == False
        # shift y into img or random
        max_shift_x = w - border_w_h[1] - box[2]
        max_shift_y = h - box[3] - border_w_h[0]
        top_left_x = np.random.randint(border_w_h[1], abs(int(max_shift_x)))
        top_left_y = np.random.randint(border_w_h[0], abs(int(max_shift_y)))
        if txt_points is None:
            context.move_to(top_left_x - int(box[0]), top_left_y - int(box[1]))
        else:
            context.move_to(txt_points[1], txt_points[0])

        context.set_source_rgb(0, 0, 0)
        context.show_text(text)

    buf = surface.get_data()
    out_img = np.frombuffer(buf, np.uint8)
    out_img.shape = (h, w, 4)
    # make image black and white
    out_img = out_img[:, :, 0]
    out_img = out_img.astype(np.float32) / 255
    # out_img = np.expand_dims(out_img, 0)
    return out_img, img_in_box
コード例 #13
0
ファイル: draw_railmap.py プロジェクト: ian2009/railmap
def cairo_png(filename, width, height):
    """A context manager which provides a Cairo context which is written to a
    PNG of the specified size upon leaving the context.
    """
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    ctx = cairo.Context(surface)

    yield ctx

    surface.write_to_png(filename)
コード例 #14
0
ファイル: render.py プロジェクト: kylestew/AlgodoneRings
    def __init_cairo(self):
        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(self.n),
                                          int(self.n))
        self.ctx = cairo.Context(self.surface)

        # special drawing surface (0-1) with 0.5,0.5 centered
        self.ctx.scale(self.n, self.n)
        self.ctx.translate(0.5, 0.5)

        self.clear_canvas()
コード例 #15
0
def sample():
    s = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200)
    c = cairo.Context(s)
    c.set_source_rgba(255, 255, 255)
    c.rectangle(0, 0, 200, 200)
    c.fill()
    c.set_source_rgba(255, 0, 0)
    c.rectangle(50, 50, 100, 100)
    c.stroke()
    Show(s).run()
コード例 #16
0
    def __init__(self, dpi):
        """
        """
        self.dpi = dpi
        self.gc = GraphicsContextCairo(renderer=self)
        self.text_ctx = cairo.Context(
            cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
        self.mathtext_parser = MathTextParser('Cairo')

        RendererBase.__init__(self)
コード例 #17
0
ファイル: test_numpy.py プロジェクト: AlfredoT11/ArbolesCA
def test_numpy():
    data = numpy.zeros((200, 200, 4), dtype=numpy.uint8)
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200, data=data)
    cr = cairo.Context(surface)
    cr.set_source_rgb(1.0, 1.0, 1.0)
    cr.paint()
    cr.arc(100, 100, 80, 0, 2*math.pi)
    cr.set_line_width(3)
    cr.set_source_rgb(1.0, 0.0, 0.0)
    cr.stroke()
コード例 #18
0
    def print_png(self, fobj, *args, **kwargs):
        width, height = self.get_width_height()

        renderer = RendererCairo(self.figure.dpi)
        renderer.set_width_height(width, height)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        renderer.set_ctx_from_surface(surface)

        self.figure.draw(renderer)
        surface.write_to_png(fobj)
コード例 #19
0
def write_png(basename, pixels, width, height):  # pragma: no cover
    """Take a pixel matrix and write a PNG file."""
    directory = os.path.join(os.path.dirname(__file__), 'results')
    if not os.path.isdir(directory):
        os.mkdir(directory)
    filename = os.path.join(directory, basename + '.png')
    cairo.ImageSurface(
        cairo.FORMAT_ARGB32, width, height,
        data=bytearray(pixels), stride=width * 4
    ).write_to_png(filename)
コード例 #20
0
ファイル: gentestutils.py プロジェクト: tigercosmos/labium
 def make_flat_image(filename, w, h, r, g, b, a):
     if os.path.exists('%s/%s' % (IMAGEOUTPUTDIR, filename)):
         return filename
     surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
     cr = cairo.Context(surface)
     cr.set_source_rgba(r, g, b, a)
     cr.rectangle(0, 0, w, h)
     cr.fill()
     surface.write_to_png('%s/%s' % (IMAGEOUTPUTDIR, filename))
     return filename
    def render_with_cairo_each(self, width, height):
        r"""

        Parameters
        ----------
        width : int
            width of the patch
        height : int
            height of the patch

        Returns
        -------
        renderings : torch.Tensor
            of shape [patches_n, primitives_n, height, width]

        """
        # prepare data buffer to render each group (patch) to
        buffer_width = cairo.ImageSurface.format_stride_for_width(
            cairo.FORMAT_A8, width)
        buffer = torch.empty((height, buffer_width),
                             dtype=torch.uint8).reshape(-1).numpy()

        renderings = torch.empty(
            [self.patches_n, self.primitives_n, height, width],
            dtype=self.dtype)

        # prepare canvas
        surface = cairo.ImageSurface(cairo.FORMAT_A8,
                                     width,
                                     height,
                                     data=memoryview(buffer),
                                     stride=buffer_width)
        with cairo.Context(surface) as ctx:
            ctx.set_operator(cairo.OPERATOR_SOURCE)
            ctx.set_line_join(cairo.LINE_JOIN_BEVEL)
            ctx.set_line_cap(cairo.LINE_CAP_BUTT)

            for patch_i in range(self.patches_n):
                for primitive_i in range(self.primitives_n):
                    ctx.set_source_rgba(0, 0, 0, 0)
                    ctx.paint()  # paint emptyness everywhere
                    ctx.set_source_rgba(0, 0, 0, 1)

                    # draw
                    self.render_single_primitive_with_cairo(
                        ctx, patch_i, primitive_i)

                    # remove int32 padding and copy data
                    renderings[patch_i,
                               primitive_i].numpy()[:] = torch.as_tensor(
                                   buffer.reshape(height,
                                                  buffer_width)[:, :width],
                                   dtype=self.dtype) / 255

        return renderings
コード例 #22
0
    def __init__(self, config, debug, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self._config = config

        if not debug:
            super().attributes("-fullscreen", True)
            super().config(cursor="none")

        self.size = config.window.width, config.window.height
        self.geometry("{}x{}".format(*self.size))
        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *self.size)
        self.context = cairo.Context(self.surface)

        self._plugins = [
            plugin.plugin(plugin.config) for plugin in config.plugins
        ]
        self._timeline = Timeline(self._config.timeline, self._plugins)
        self._event_list = EventList(config.event_list)
        self._app_heading = AppHeading(self._config.app_heading)
        self._clock = Clock(self._config.clock)

        self.label = tkinter.Label(self)
        self.label.pack(expand=True, fill="both")

        for p in self._plugins:
            p.start()

        try:
            while True:
                events = []

                now = datetime.datetime.now()

                for p in self._plugins:
                    events += p.get_timeline_items(now,
                                                   now + self._config.timespan)

                events.sort(key=lambda e: e.start())

                self._event_list.set_timeline_events(events)
                self._timeline.set_timeline_events(events)

                self.render(now)
                self.update_idletasks()
                self.update()

                time.sleep(5)

        except KeyboardInterrupt:
            print("")
            print("Stopping all plugins.")
            for p in self._plugins:
                p.stop()
            print("Exiting.")
コード例 #23
0
def render_with_skeleton(data, dimensions, data_representation='vahe', line_width=1, node_size=4, control_line_width=.5, control_node_size=2, line_color=(1,1,0), node_color=(1,0,0), controls_color=(0,0,1), linecaps='square', linejoin='miter'):
    if data_representation != 'vahe':
        raise NotImplementedError
    # prepare data buffer
    width, height = dimensions
    buffer_width = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_RGB24, width)
    image = np.ndarray(shape=(height, buffer_width), dtype=np.uint8).ravel()

    # get drawing parameters
    linecaps = _linecaps[linecaps]
    linejoin = _linejoin[linejoin]

    # draw
    surface = cairo.ImageSurface(cairo.FORMAT_RGB24, *dimensions, data=memoryview(image), stride=buffer_width)

    if byteorder == 'little':
        rgb_slice = slice(0,3)
        line_color = reversed(line_color)
        node_color = reversed(node_color)
        controls_color = reversed(controls_color)
    else:
        rgb_slice = slice(1,4)
    with cairo.Context(surface) as ctx:
        ctx.set_operator(cairo.OPERATOR_SOURCE)
        ctx.set_line_join(linejoin)
        ctx.set_line_cap(linecaps)

        # ignore r,g,b -- draw in alpha
        set_color_to_bg = lambda: ctx.set_source_rgb(1, 1, 1) # white
        set_color_to_fg = lambda: ctx.set_source_rgb(0, 0, 0) # black

        # fill bg
        set_color_to_bg()
        ctx.paint()

        # draw
        set_color_to_fg()
        _render_data[data_representation](data, ctx)

        # draw skeleton
        edges, nodes, controls = _make_skeleton[data_representation](data, line_width=line_width, node_size=node_size, control_line_width=control_line_width, control_node_size=control_node_size)

        ctx.set_source_rgb(*line_color)
        _render_data[data_representation](edges, ctx)

        ctx.set_source_rgb(*node_color)
        _render_data[data_representation](nodes, ctx)

        ctx.set_source_rgb(*controls_color)
        _render_data[data_representation](controls, ctx)

    # remove alpha padding
    image = image.reshape(height, -1, 4)[:, :width, rgb_slice]

    return image
コード例 #24
0
def vector_to_raster(vector_images,
                     side=28,
                     line_diameter=16,
                     max_padding=4,
                     bg_color=(0, 0, 0),
                     fg_color=(1, 1, 1)):
    """
    padding and line_diameter are relative to the original 256x256 image.
    """

    original_side = 256.
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, side, side)

    raster_images = []
    for vector_image in vector_images:
        rand = int(random.random() * max_padding)
        padding = rand**2
        ctx = cairo.Context(surface)
        ctx.set_antialias(cairo.ANTIALIAS_BEST)
        ctx.set_line_cap(cairo.LINE_CAP_ROUND)
        ctx.set_line_join(cairo.LINE_JOIN_ROUND)
        # ctx.set_line_width(line_diameter * math.sqrt(rand))
        # ctx.set_line_width(line_diameter * rand)
        # print(rand, padding)
        ctx.set_line_width(line_diameter * 8 / (1 + ((20 - rand) / 6)))
        # scale to match the new size
        # add padding at the edges for the line_diameter
        # and add additional padding to account for antialiasing
        total_padding = padding * 2. + line_diameter
        new_scale = float(side) / float(original_side + total_padding)
        ctx.scale(new_scale, new_scale)
        ctx.translate(total_padding / 2., total_padding / 2.)

        # clear background
        ctx.set_source_rgb(*bg_color)
        ctx.paint()

        bbox = np.hstack(vector_image).max(axis=1)
        offset = ((original_side, original_side) - bbox) / 2.
        offset = offset.reshape(-1, 1)
        centered = [stroke + offset for stroke in vector_image]

        # draw strokes, this is the most cpu-intensive part
        ctx.set_source_rgb(*fg_color)
        for xv, yv in centered:
            ctx.move_to(xv[0], yv[0])
            for x, y in zip(xv, yv):
                ctx.line_to(x, y)
            ctx.stroke()

        data = surface.get_data()
        raster_image = np.copy(np.asarray(data)[::4])
        raster_images.append(raster_image)

    return raster_images
コード例 #25
0
 def __init__(self, width, height):
     """
     Constructor. Create a Cairo image surface and a render context, and disables
     anti-aliasing for the image to keep the lines sharp.
     """
     self.width = width
     self.height = height
     self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
     self.context = cairo.Context(self.surface)
     self.context.scale(width, height)
     self.context.set_antialias(cairo.ANTIALIAS_NONE)
コード例 #26
0
    def __init__(self, dpi):
        """
        """
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))
        self.dpi = dpi
        self.gc = GraphicsContextCairo(renderer=self)
        self.text_ctx = cairo.Context(
            cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
        self.mathtext_parser = MathTextParser('Cairo')

        RendererBase.__init__(self)
コード例 #27
0
def paint_text(text, w, h, rotate=False, ud=False, multi_fonts=False):
    surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)
    # 'with... as ... : ' structure
    with cairo.Context(surface) as context:
        context.set_source_rgb(1, 1, 1)  # White
        context.paint()
        # this font list works in CentOS 7
        if multi_fonts:
            fonts = [
                'Century Schoolbook', 'Courier', 'STIX', 'URW Chancery L',
                'FreeMono'
            ]
            context.select_font_face(
                np.random.choice(fonts),  # np.random.choice(list)
                cairo.FONT_SLANT_NORMAL,
                np.random.choice(
                    [cairo.FONT_WEIGHT_BOLD, cairo.FONT_WEIGHT_NORMAL]))
        else:
            context.select_font_face('Courier', cairo.FONT_SLANT_NORMAL,
                                     cairo.FONT_WEIGHT_BOLD)
        context.set_font_size(25)
        box = context.text_extents(text)
        border_w_h = (4, 4)
        if box[2] > (w - 2 * border_w_h[1]) or box[3] > (h -
                                                         2 * border_w_h[0]):
            # 'raise IOError()'
            raise IOError(
                ('Could not fit string into image.'
                 'Max char count is too large for given image width.'))

        # teach the RNN translational invariance by
        # fitting text box randomly on canvas, with some room to rotate
        max_shift_x = w - box[2] - border_w_h[0]
        max_shift_y = h - box[3] - border_w_h[1]
        top_left_x = np.random.randint(0,
                                       int(max_shift_x))  # get one int value
        if ud:
            top_left_y = np.random.randint(0, int(max_shift_y))
        else:
            top_left_y = h // 2
        context.move_to(top_left_x - int(box[0]), top_left_y - int(box[1]))
        context.set_source_rgb(0, 0, 0)
        context.show_text(text)

    buf = surface.get_data()
    a = np.frombuffer(buf, np.uint8)  #  'np.frombuffer()'
    a.shape = (h, w, 4)
    a = a[:, :, 0]  # grab single channel
    a = a.astype(np.float32) / 255
    a = np.expand_dims(a, 0)  # 'np.expand_dims()'
    if rotate: a = image.random_rotation(a, 3 * (w - top_left_x) / w + 1)

    a = speckle(a)  # call pre-defined 'sepeckle()' function
    return a
コード例 #28
0
 def test_range(self):
     surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 500, 500)
     opt = {'axis': {'x': {'range': (1, 10)}, 'y': {'range': (1.0, 10.0)}}}
     ch = pycha.chart.Chart(surface, opt)
     dataset = (('dataset1', ([0, 1], [1, 1], [2, 3])), )
     ch.addDataset(dataset)
     ch._updateXY()
     self.assertAlmostEqual(ch.xrange, 9, 4)
     self.assertAlmostEqual(ch.yrange, 9, 4)
     self.assertAlmostEqual(ch.xscale, 0.1111, 4)
     self.assertAlmostEqual(ch.yscale, 0.1111, 4)
コード例 #29
0
    def __init__(self, size, width):
        self.center = [size / 2, size / 2]
        self.size = size
        self.width = width
        self.surface = cairo.ImageSurface(cairo.FORMAT_RGB24, size, size)
        self.context = cairo.Context(self.surface)
        self.context.set_source_rgb(*WHITE)
        self.context.paint()

        self.last_rec = True
        self.last_black = False
コード例 #30
0
ファイル: drawer.py プロジェクト: m-col/qtile
    def __init__(self, qtile: Qtile, win: Internal, width: int, height: int):
        base.Drawer.__init__(self, qtile, win, width, height)

        self._stride = cairocffi.ImageSurface.format_stride_for_width(
            cairocffi.FORMAT_ARGB32, self.width)
        self._source = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, width,
                                              height)
        with cairocffi.Context(self._source) as context:
            # Initialise surface to all black
            context.set_source_rgba(*utils.rgb("#000000"))
            context.paint()