def set_bounds(self, bounds, new_surface=False): origin_in_inch = (bounds[0][0], bounds[1][0]) size_in_inch = (abs(bounds[0][1] - bounds[0][0]), abs(bounds[1][1] - bounds[1][0])) size_in_pixels = self.scale_point(size_in_inch) self.origin_in_inch = origin_in_inch if self.origin_in_inch is None else self.origin_in_inch self.size_in_inch = size_in_inch if self.size_in_inch is None else self.size_in_inch self._xform_matrix = cairo.Matrix(xx=1.0, yy=-1.0, x0=-self.origin_in_pixels[0], y0=self.size_in_pixels[1]) if (self.surface is None) or new_surface: self.surface_buffer = tempfile.NamedTemporaryFile() self.surface = cairo.SVGSurface(self.surface_buffer, size_in_pixels[0], size_in_pixels[1]) self.output_ctx = cairo.Context(self.surface)
def _draw( self, offsetx: int = 0, offsety: int = 0, width: Optional[int] = None, height: Optional[int] = None, ): if offsetx > self._win.width: # type: ignore return # We need to set the current draw area so we can compare to the previous one self.current_rect = (offsetx, offsety, width, height) # rect_changed = current_rect != self.previous_rect if not self.needs_update: return # Keep track of latest rect covered by this drawwer self.previous_rect = self.current_rect # Make sure geometry doesn't extend beyond texture if width is None: width = self.width if width > self._win.width - offsetx: # type: ignore width = self._win.width - offsetx # type: ignore if height is None: height = self.height if height > self._win.height - offsety: # type: ignore height = self._win.height - offsety # type: ignore # Paint RecordingSurface operations our window's ImageSurface with cairocffi.Context(self._source) as context: context.set_source_surface(self.surface) context.paint() # Copy drawn ImageSurface data into rendered wlr_texture self._win.texture.write_pixels( # type: ignore self._stride, width, height, cairocffi.cairo.cairo_image_surface_get_data( self._source._pointer), dst_x=offsetx, dst_y=offsety, ) self._win.damage() # type: ignore
def new_render_layer(self, color=None, mirror=False): size_in_pixels = self.scale_point(self.size_in_inch) matrix = copy.copy(self._xform_matrix) layer = cairo.SVGSurface(None, size_in_pixels[0], size_in_pixels[1]) ctx = cairo.Context(layer) if self.invert: ctx.set_source_rgba(0.0, 0.0, 0.0, 1.0) ctx.set_operator(cairo.OPERATOR_OVER) ctx.paint() if mirror: matrix.xx = -1.0 matrix.x0 = self.origin_in_pixels[0] + self.size_in_pixels[0] self.ctx = ctx self.ctx.set_matrix(matrix) self.active_layer = layer self.active_matrix = matrix
def paint(self, screen: Screen, image_path: str, mode: str | None = None) -> None: try: with open(image_path, "rb") as f: image, _ = cairocffi.pixbuf.decode_to_image_surface(f.read()) except IOError as e: logger.error("Wallpaper: %s" % e) return surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, screen.width, screen.height) with cairocffi.Context(surface) as context: if mode == "fill": context.rectangle(0, 0, screen.width, screen.height) context.clip() image_w = image.get_width() image_h = image.get_height() width_ratio = screen.width / image_w if width_ratio * image_h >= screen.height: context.scale(width_ratio) else: height_ratio = screen.height / image_h context.translate(-(image_w * height_ratio - screen.width) // 2, 0) context.scale(height_ratio) elif mode == "stretch": context.scale( sx=screen.width / image.get_width(), sy=screen.height / image.get_height(), ) context.set_source_surface(image) context.paint() stride = surface.format_stride_for_width(cairocffi.FORMAT_ARGB32, screen.width) surface.flush() texture = Texture.from_pixels( self.core.renderer, DRM_FORMAT_ARGB8888, stride, screen.width, screen.height, cairocffi.cairo.cairo_image_surface_get_data(surface._pointer), ) # mypy struggles to understand this. See: https://github.com/python/mypy/issues/11513 outputs = [ output for output in self.core.outputs if output.wlr_output.enabled # type: ignore ] outputs[screen.index].wallpaper = texture
def __init__(self,logo_matrix,ytick=10): #BaseLogo.__init__(self) self.logo_matrix = logo_matrix self.ytick = ytick #Set y-ticks self.min_value = np.min(self.logo_matrix) self.max_value = np.max(self.logo_matrix) if self.min_value < 0: self.has_neg_values = True else: self.has_neg_values = False self.x =0 self.y =0 self.seq_len = self.logo_matrix.shape[1] self.font_size =30 #Width of each nucleotide in the figure self.bp_width = self.font_size +1 if self.has_neg_values: self.height=256 #This is distinct from pwm code else: self.height=128 #self.height = int(self.max_value) #print "Height of figure", self.height #if self.height > 300: # print "Height of HeightLogo",self.height,"is too high" # print "Setting to 300 pixels" # self.height=300 self.x_axis_line = self.height-5 self.x_offset = 15 self.x_axis_pad = 2 self.width = self.bp_width*self.seq_len+self.x_offset+self.x_axis_pad self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width,self.height) self.context = cairo.Context(self.surface) self.context.select_font_face("Monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) self.context.set_font_size(self.font_size) self.context.set_source_rgb(0.1, 0.1, 0.1) self.context.scale(1,1)
def text2svg(self): """Internally used function. Convert the text to SVG using Pango """ size = self.size * 10 line_spacing = self.line_spacing * 10 dir_name = config.get_dir("text_dir") if not os.path.exists(dir_name): os.makedirs(dir_name) hash_name = self.text2hash() file_name = os.path.join(dir_name, hash_name) + ".svg" if os.path.exists(file_name): return file_name surface = cairocffi.SVGSurface(file_name, 600, 400) context = cairocffi.Context(surface) context.move_to(START_X, START_Y) settings = self.text2settings() offset_x = 0 last_line_num = 0 layout = pangocairocffi.create_layout(context) layout.set_width(pangocffi.units_from_double(600)) for setting in settings: family = setting.font style = self.str2style(setting.slant) weight = self.str2weight(setting.weight) text = self.text[setting.start:setting.end].replace("\n", " ") fontdesc = pangocffi.FontDescription() fontdesc.set_size(pangocffi.units_from_double(size)) if family: fontdesc.set_family(family) fontdesc.set_style(style) fontdesc.set_weight(weight) layout.set_font_description(fontdesc) if setting.line_num != last_line_num: offset_x = 0 last_line_num = setting.line_num context.move_to(START_X + offset_x, START_Y + line_spacing * setting.line_num) pangocairocffi.update_layout(context, layout) layout.set_text(text) logger.debug(f"Setting Text {text}") pangocairocffi.show_layout(context, layout) offset_x += pangocffi.units_to_double(layout.get_size()[0]) surface.finish() return file_name
def main(verts, depth, size): size = 600 bg_color = (1, 1, 1) # color outside the unit circle. arc_color = (0, 0, 0) # color of the arcs. funda_domain_color = (0.5, 0.5, 0.5) # color of the fundamental domain. surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size) ctx = cairo.Context(surface) ctx.translate(size / 2.0, size / 2.0) ctx.scale(size / 2.0, -size / 2.0) ctx.set_source_rgb(*bg_color) ctx.paint() ctx.set_line_width(0.01) ctx.set_source_rgb(*arc_color) ctx.arc(0, 0, 1, 0, 2 * np.pi) ctx.stroke_preserve() ctx.set_source_rgb(0.5, 0.5, 0.5) ctx.fill_preserve() ctx.clip() # only the region inside the unit circle will be shown. for word, state, circle in traverse(verts, depth): d = len(word) - 1.0 try: z, r = matrix_to_circle(circle) ctx.arc(z.real, z.imag, r, 0, 2 * np.pi) except: # We must distinguish between the inner and outer side of a line. # We think the left hand of z is the inner part. # To fill the intersection of this half plane and the unit disk # we simply draw a 1x2 rectangle. z = matrix_to_circle(circle) ctx.move_to(z.real, z.imag) ctx.line_to(z.real - z.imag, z.real + z.imag) ctx.line_to(-z.real - z.imag, z.real - z.imag) ctx.line_to(-z.real, -z.imag) ctx.close_path() ctx.set_source_rgb(*hue(d / depth)) ctx.fill_preserve() ctx.set_source_rgb(*arc_color) ctx.set_line_width((d + 2) * 0.005 / (d + 1)) ctx.stroke() surface.write_to_png("infx3_tiling.png")
def paint_text(text, w, h, rotate=False, ud=False, multi_fonts=False): 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) return a
def p2(w, h): surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context (surface) ctx.set_source_rgb(0, 0, 0) ctx.rectangle(0,0,w,h) ctx.fill() x, y = 0, 0 xp, yp = point_to_pixel(x, y, w, h) # xp -= r # yp -= r # Subtract the radius ctx.set_source_rgb(1, 1, 1) ctx.rectangle(xp, yp, w/7, h/7) ctx.rectangle(xp-w/5, yp-h/5, w/5, h/5) ctx.fill() ctx.stroke() buf = np.frombuffer(surface.get_data(), np.uint8) img = buf.reshape(w, h, 4)[:,:,0] return surface, img, x, y
def draw(self, fill=True, line=True, outline=False, order=['ol', 'l', 'f'], *, target): '''Draws the Shape to the target's surface Parameters ---------- fill: bool (optional - default: True) - Whether to draw the fill of the shape object line: bool (optional - default: True) - Whether to draw the stroke (or line) of the shape object outline: bool (optional - default: False) - Whether to draw the outline of the shape object Returns ------- None ''' self.ctx = cairo.Context(target=self.surface.cairo_surface)
def test_rtl_text_to_svgobject() -> None: """Checks number of submobjects generated when directly called using ``SVGMobject``""" size = 1 text = RTL_TEXT.replace("\n", "") temp_pango_text = Text(text, size=1) surface = cairocffi.SVGSurface(filename, WIDTH, HEIGTH) context = cairocffi.Context(surface) context.move_to(START_X, START_Y) layout = pangocairocffi.create_layout(context) layout.set_width(pangocffi.units_from_double(WIDTH)) fontdesc = pangocffi.FontDescription() fontdesc.set_size(pangocffi.units_from_double(size * 10)) layout.set_font_description(fontdesc) layout.set_text(text) pangocairocffi.show_layout(context, layout) surface.finish() assert compare_SVGObject_with_PangoText(temp_pango_text, filename)
def _get_text_size(self, text, padding=2, file_format='pdf'): """ """ try: import cairocffi as cairo except ImportError: import cairo # Use dummy surface to determine text extents surface = create_new_surface(file_format) cr = cairo.Context(surface) cr.set_font_size(self.options['fontSizeNormal']) extents = cr.text_extents(text) width = extents[2] + 2 * padding height = extents[3] + 2 * padding return [0, 0, width, height]
def _new_render_layer(self, color=None, mirror=False): size_in_pixels = self.scale_point(self.size_in_inch) matrix = copy.copy(self._xform_matrix) layer = cairo.SVGSurface(None, size_in_pixels[0], size_in_pixels[1]) ctx = cairo.Context(layer) ctx.scale(1, -1) ctx.translate(-(self.origin_in_inch[0] * self.scale[0]), (-self.origin_in_inch[1] * self.scale[0]) - size_in_pixels[1]) if self.invert: ctx.set_operator(cairo.OPERATOR_OVER) ctx.paint() if mirror: matrix.xx = -1.0 matrix.x0 = self.origin_in_pixels[0] + self.size_in_pixels[0] self.ctx = ctx self.active_layer = layer self.active_matrix = matrix
def main(hexagonsize, imgsize): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, imgsize, imgsize) ctx = cairo.Context(surface) # we will put the center of the hexagon at the origin a, b, c = hexagonsize ctx.translate(imgsize / 2.0, imgsize / 2.0) extent = max(c, a * SQRT3 / 2, b * SQRT3 / 2) + 1 ctx.scale(imgsize / (extent * 2.0), -imgsize / (extent * 2.0)) ctx.translate(-b * SQRT3 / 2, -c / 2.0) # paint background ctx.set_source_rgb(1, 1, 1) ctx.paint() T = LozengeTiling(hexagonsize).run_cftp() draw(ctx, T) surface.write_to_png("random_lozenge_tiling.png")
def test_tabs_replace() -> None: """Checks whether are there in end svg image. Pango should handle tabs and line breaks.""" size = 1 temp_pango_text = Text("hello\thi\nf") assert temp_pango_text.text == "hellohif" surface = cairocffi.SVGSurface(filename, WIDTH, HEIGTH) context = cairocffi.Context(surface) context.move_to(START_X, START_Y) layout = pangocairocffi.create_layout(context) layout.set_width(pangocffi.units_from_double(WIDTH)) fontdesc = pangocffi.FontDescription() fontdesc.set_size(pangocffi.units_from_double(size * 10)) layout.set_font_description(fontdesc) layout.set_text("hellohif") pangocairocffi.show_layout(context, layout) surface.finish() assert compare_SVGObject_with_PangoText(temp_pango_text, filename)
def draw_des(ds, es, width, height): ## Cairo STUFF surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context (surface) ctx.set_source_rgb(1,1,1) ctx.rectangle(0,0,width,height) ctx.fill() def circle(ctx, x, y, size): ctx.arc(x, y, size, 0, 2 * math.pi) ## Back to the good stuff # Connect detectors to emitters ctx.set_line_width(2) ctx.set_source_rgb(0, 0.5, 0) for e in es: for d in ds: ctx.move_to(*point_to_pixel(e['r']*math.cos(e['a']), e['r']*math.sin(e['a']), width, height)) # Wow that's a nifty trick!! ctx.line_to(*point_to_pixel(d['r']*math.cos(d['a']), d['r']*math.sin(d['a']), width, height)) ctx.stroke() # Draw detectors ctx.set_source_rgb(0, 0, 1) for d in ds: cx, cy = point_to_pixel(d['r']*math.cos(d['a']), d['r']*math.sin(d['a']), width, height) circle(ctx, cx, cy, 20) ctx.fill() ctx.stroke() # print(cx, cy) # Draw Emitters ctx.set_source_rgb(1, 0, 1) for e in es: cx, cy = point_to_pixel(e['r']*math.cos(e['a']), e['r']*math.sin(e['a']), width, height) circle(ctx, cx, cy, 10) ctx.fill() ctx.stroke() # print(cx, cy) return surface
def render_png(self, writer, width, height): """ Renders this svg object as a PNG @param writer - any file like object that has a write method @param width - width of the png @param height - height of the png """ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = cairo.Context(surface) for op in self.operations: if op.type == 'line': context.move_to(op.x + .5, op.y + .5) context.line_to(op.x1 + .5, op.y1 + .5) context.set_line_width(op.stroke) r, g, b = RGBTuple(op.color) context.set_source_rgba(r, g, b, 1) context.stroke() elif op.type == 'text': red, green, blue = RGBTuple(op.color) context.set_source_rgba(red, green, blue, 1) context.set_font_size(op.size) context.move_to(op.x, op.y) context.rotate(radians(op.rotate)) context.show_text(op.text) context.rotate(0) elif op.type == 'rect': context.rectangle(op.x, op.y, op.width, op.height) if op.color and op.color <> 'None': red, green, blue = RGBTuple(op.color) context.set_source_rgba(red, green, blue, 1) context.set_line_width(op.stroke) context.stroke_preserve() if op.fill and op.fill <> 'None': r, g, b = RGBTuple(op.fill) context.set_source_rgba(r, g, b, 1) else: context.set_source_rgba(0, 0, 0, 0) context.fill() surface.write_to_png(writer)
def __init__(self, variation, variation_max=None, curve=None): self.SURFACE_HEIGHT = 790. self.SURFACE_WIDTH = 590. self.edge_indent = 30. self.rose_centre_x = self.SURFACE_WIDTH / 2 self.rose_centre_y = self.SURFACE_HEIGHT - self.rose_centre_x self.rose_width = 30. self.inter_rose_gap = 2. self.text_line_height = 1.2 self.width_cardinal = 3 # N, S, E, W # self.width_ordinal = 0.1 # NE, SW, SE, NE self.width_major = 1 self.width_minor = 0.5 self.width_tick = 0.1 (handle, cairo_tmp) = tempfile.mkstemp('.pdf', 'omnirose-rose') os.close(handle) self.filename = cairo_tmp self.surface = cairo.PDFSurface(self.filename, self.SURFACE_WIDTH, self.SURFACE_HEIGHT) self.context = cairo.Context(self.surface) self.curve = curve self.variation = variation if variation_max is None: self.variation_max = variation else: self.variation_max = variation_max self.magnetic_background_colour_rgba = (1, 0.95, 0.95, 1) self.magnetic_text_colour_rgba = (0.2, 0, 0, 1) self.true_background_colour_rgba = (0.95, 1, 0.95, 1) self.true_text_colour_rgba = (0, 0.2, 0, 1) self.compass_background_colour_rgba = (0.95, 0.95, 1, 1) self.compass_text_colour_rgba = (0, 0, 0.2, 1)
def paint(self, screen, image_path, mode=None): try: with open(image_path, 'rb') as f: image, _ = cairocffi.pixbuf.decode_to_image_surface(f.read()) except IOError as e: logger.error('Wallpaper: %s' % e) return surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, screen.width, screen.height) with cairocffi.Context(surface) as context: if mode == 'fill': context.rectangle(0, 0, screen.width, screen.height) context.clip() image_w = image.get_width() image_h = image.get_height() width_ratio = screen.width / image_w if width_ratio * image_h >= screen.height: context.scale(width_ratio) else: height_ratio = screen.height / image_h context.translate( -(image_w * height_ratio - screen.width) // 2, 0) context.scale(height_ratio) elif mode == 'stretch': context.scale( sx=screen.width / image.get_width(), sy=screen.height / image.get_height(), ) context.set_source_surface(image) context.paint() stride = surface.format_stride_for_width(cairocffi.FORMAT_ARGB32, screen.width) surface.flush() texture = Texture.from_pixels( self.core.renderer, DRM_FORMAT_ARGB8888, stride, screen.width, screen.height, cairocffi.cairo.cairo_image_surface_get_data(surface._pointer)) outputs = [ output for output in self.core.outputs if output.wlr_output.enabled ] outputs[screen.index].wallpaper = texture
def test_font_face() -> None: """Checks font face using submobject len""" size = 1 text = RTL_TEXT.replace("\n", "") font_face = "sans" temp_pango_text = Text(text, size=1, font=font_face) surface = cairocffi.SVGSurface(filename, WIDTH, HEIGTH) context = cairocffi.Context(surface) context.move_to(START_X, START_Y) layout = pangocairocffi.create_layout(context) layout.set_width(pangocffi.units_from_double(WIDTH)) fontdesc = pangocffi.FontDescription() fontdesc.set_family(font_face) fontdesc.set_size(pangocffi.units_from_double(size * 10)) layout.set_font_description(fontdesc) layout.set_text(text) pangocairocffi.show_layout(context, layout) surface.finish() assert compare_SVGObject_with_PangoText(temp_pango_text, filename)
def __init__(self, width, height): self.width = width self.height = height self.connection = xcb.connect() self.xsetup = self.connection.get_setup() self.window = self.connection.generate_id() self.pixmap = self.connection.generate_id() self.gc = self.connection.generate_id() events = [self.xsetup.roots[0].white_pixel, EventMask.ButtonPress | EventMask.ButtonRelease | EventMask.EnterWindow | EventMask.LeaveWindow | EventMask.Exposure | EventMask.PointerMotion | EventMask.ButtonMotion | EventMask.KeyPress | EventMask.KeyRelease] self.connection.core.CreateWindow(self.xsetup.roots[0].root_depth, self.window, # Parent is the root window self.xsetup.roots[0].root, 0, 0, self.width, self.height, 0, WindowClass.InputOutput, self.xsetup.roots[0].root_visual, CW.BackPixel | CW.EventMask, events) self.connection.core.CreatePixmap(self.xsetup.roots[0].root_depth, self.pixmap, self.xsetup.roots[0].root, self.width, self.height) self.connection.core.CreateGC(self.gc, self.xsetup.roots[0].root, GC.Foreground | GC.Background, [self.xsetup.roots[0].black_pixel, self.xsetup.roots[0].white_pixel]) self.surface = cairo.XCBSurface (self.connection, self.pixmap, self.xsetup.roots[0].allowed_depths[0].visuals[0], self.width, self.height) self.context = cairo.Context(self.surface) self.surfaces = {"screen":self.surface} self.contexts = {"screen":self.context} self.layers = OrderedDict() #Layer roots self.lastupdate = {} self.lastdrawn = {}
def vectorize(self, dir): WIDTH, HEIGHT = BotInfo.size_x, BotInfo.size_y surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) cr = cairo.Context(surface) cr.set_source_rgb(self.color[0], self.color[1], self.color[2]) cr.translate(WIDTH / 2, HEIGHT / 2) cr.scale(WIDTH, HEIGHT) cr.rotate(math.radians(180 - dir)) cr.rectangle(-0.2, -0.3, 0.4, 0.6) cr.fill() cr.set_source_rgb(BotImage.COLOURS["ORANGE"][0], BotImage.COLOURS["ORANGE"][1], BotImage.COLOURS["ORANGE"][2]) cr.rectangle(0.2, 0.05, 0.1, 0.2) cr.fill() cr.rectangle(-0.2, 0.05, -0.1, 0.2) cr.fill() return surface
def write_png_center(width, target, markup): pt_per_mm = 72 / 25.4 height = 1080 surface = cairocffi.PDFSurface(target, width, height) surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, width, height) surface.set_mime_data("image/png", None) context = cairocffi.Context(surface) context.translate(0, 300) #context.rotate(-0.2) layout = gobject_ref(pangocairo.pango_cairo_create_layout( context._pointer)) pango.pango_layout_set_width(layout, units_from_double(width)) pango.pango_layout_set_alignment(layout, pango.PANGO_ALIGN_CENTER) markup = ffi.new('char[]', markup.encode('utf8')) pango.pango_layout_set_markup(layout, markup, -1) pangocairo.pango_cairo_show_layout(context._pointer, layout) surface.write_to_png(target)
def _make_surface(self, output_path, image_format, image_width, crop_margin): """ Make the relevant Cairo surface and context with appropriate sizing. """ if image_format == "PNG": surface = self._make_raster_surface(image_width, crop_margin) scale = 1 else: surface, scale, crop_margin = self._make_vector_surface( output_path, image_format, image_width, crop_margin ) context = _cairo.Context(surface) if crop_margin is not None: crop_margin = crop_margin / scale context.translate( -self._block_extents[0] + crop_margin, -self._block_extents[1] + crop_margin, ) return surface, context, scale
def render_scene_as_input(self, scene, return_sequence=False, draw_boxes=False): surface = cairo.ImageSurface.create_from_png(self.background_path()) ctx = cairo.Context(surface) assert (len(scene['segments']) > 0) if draw_boxes and scene.get('boxes', None) is None: scene = self.create_bboxes(scene) sequence = [] for i in range(len(scene['segments'])): pos = scene['positions'][i] flip = scene['flips'][i] scale = self.cfg.scales[scene['scales'][i]] segment_image = cv2.imread(self.segment_path(scene['segments'][i]), cv2.IMREAD_UNCHANGED) segment_image = cv2.resize(segment_image, (0, 0), fx=scale, fy=scale) H, W, _ = segment_image.shape if flip == 1: segment_image = np.flip(segment_image, axis=1).copy() segment_surf = cairo.ImageSurface.create_for_data( segment_image, cairo.FORMAT_ARGB32, W, H) ox = pos[0] - W / 2 oy = pos[1] - H / 2 ctx.save() ctx.translate(ox, oy) ctx.set_source_surface(segment_surf) ctx.paint() ctx.restore() if draw_boxes: xyxy = scene['boxes'][i] paint_box(ctx, (0, 1, 0), xyxy) frame = surface_to_image(surface) frame = cv2.resize( frame, (self.cfg.input_size[1], self.cfg.input_size[0])) sequence.append(frame) if return_sequence: return np.stack(sequence, axis=0) else: return sequence[-1]
def __init__(self, input_file, output_file, min_z, max_z): self.mode = "rel" self.filename = input_file self.units = "mm" self.x = 0 self.y = 0 self.z = 0 self.min_z = min_z self.max_z = max_z self.layer_lines = 0 self.surface = cairo.PDFSurface(output_file, 1440, 1440) self.context = cairo.Context(self.surface) self.context.set_source_rgb(1, 1, 1) # White self.context.paint() self.context.set_source_rgb(0, 0, 0) self.context.set_line_width(0.1)
def get_custom_transformation(pair, trim_out_of_bounds=True): visualization_path = os.path.join(pair.base, "custom_transformation", "visualization", pair.stem(extension=".png")) create_folders(visualization_path) image = cairo.ImageSurface.create_from_png(pair.img) image = convert_to_grayscale(image) context = cairo.Context(image) page_data = pair.extract_ground_truth() lines = [] for i, line in enumerate(page_data): steps = [] for j, lf in enumerate(line["lf"]): step = Step.get_from(lf) if step.is_within(image): steps.append(step) for k, step in enumerate(steps): color = (255, 0, 0) if k == 0 else ((0, 0, 255) if k == len(steps) - 1 else (0, 255, 0)) draw_custom_lf(context, step, color) sol = steps[0] eol = steps[-1] lines.append({ "steps": list(map(lambda x: x.__dict__, steps)), "text": line["ground_truth"] }) image.write_to_png(visualization_path) return { "origin": pair.base, "basename": pair.stem(), "lines": lines, "image": pair.img, "xml": pair.transformation_xml_path, }
def draw_box_shadows(context, box, shadows, inset): box = box[0] for shadow in reversed(shadows): x, y, blur_radius, spread_radius, shadow_inset, color = shadow if inset != shadow_inset: continue blur_radius = int(blur_radius) spread_radius = int(spread_radius) offset = blur_radius + spread_radius bx, by, bw, bh = box[:4] blur = AlphaBoxBlur.from_radiuses((bx, by, bw, bh), (spread_radius, spread_radius), (blur_radius, blur_radius)) mask_x, mask_y, mask_width, mask_height = blur.get_rect() mask_data = array('B', b'\x00' * blur.get_surface_allocation_size()) mask_surface = cairo.ImageSurface( cairo.FORMAT_A8, # Single channel, one byte per pixel. mask_width, mask_height, mask_data, blur.get_stride()) mask_context = cairo.Context(mask_surface) mask_context.rectangle(bx - mask_x, by - mask_y, bw, bh) mask_context.fill() blur.blur_array(mask_data) if len(color) == 3: context.set_source_rgb(*color) elif len(color) == 4: context.set_source_rgba(*color) context.mask_surface(mask_surface, x + mask_x, y + mask_y) context.fill() context.save() context.translate(x + bx - offset, y + by - offset) context.restore()
def gabarit(): print("Génération du gabarit ...", end=' ') import draw_cairo_prj imagesurface = cairo.ImageSurface( cairo.FORMAT_ARGB32, 2100, 2970) #cairo.FORMAT_ARGB32,cairo.FORMAT_RGB24 ctx = cairo.Context(imagesurface) e = 29 ctx.scale(e, e) # print dir(draw_cairo_prj) pos = {} taille = {} for attr in dir(draw_cairo_prj): if attr[:3] == 'pos': pos[attr[3:]] = attr if attr[:6] == 'taille': taille[attr[6:]] = attr print(pos, taille) ctx.set_line_width(5.0 / e) for k, p in list(pos.items()): if k in list(taille.keys()): x, y = getattr(draw_cairo_prj, p) w, h = getattr(draw_cairo_prj, taille[k]) try: ctx.rectangle(x, y, w, h) ctx.stroke() show_text_rect(ctx, k, (x, y, w, h), fontsizeMinMax=(-1, 30.0 / e), wrap=False, couper=False) except: print(" ", k, " : ", x, y, w, h) imagesurface.write_to_png('gabarit_prj.png')
def draw(): global dest, width, height ims = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) cr = cairo.Context(ims) def layer(color, anchor, head, frequency, amplitude, noise): values = sequence.get_seq(frequency, amplitude, noise) values[len(values)-1] = values[0] cr.set_source_rgb(color.r, color.g, color.b) cr.move_to(0, anchor) for x in range(0, len(values)): cr.line_to(x * (width / float(len(values) - 1)), head + values[x]) cr.line_to(width, anchor) cr.line_to(0, anchor) cr.fill() layers = 8 #moss #colors = sequence.get_color_seq( color.rgb(3, 193, 54), color.rgb(46, 97, 102), 4) #colors += sequence.get_color_seq( color.rgb( 63, 79, 112), color.rgb( 23, 23, 70), 4) #moss-mod #colors = sequence.get_color_seq( color.rgb(3, 193, 54), color.rgb( 10, 10, 45), layers) #moss-bottom #colors = sequence.get_color_seq( color.rgb( 23, 23, 60), color.rgb(0, 0, 20), layers) #vent colors = sequence.get_color_seq( color.rgb(222, 14, 1), color.rgb(102, 45, 60), 4) colors += sequence.get_color_seq( color.rgb( 44, 53, 77), color.rgb( 28, 28, 70), 4) #surf #colors = sequence.get_color_seq( color.rgb(244, 200, 88), color.rgb(183, 127, 5), 3) #colors += [color.rgb(214, 251, 252)] #colors += sequence.get_color_seq( color.rgb( 47, 233, 237), color.rgb( 15, 87, 221), 4) layer(colors[0], height, 0, 2, 0, "noise") for num in range(0, layers-1): layer(colors[num+1], height, height * (float(num + 1)/float(layers)), 5, 25, "noise") ims.write_to_png(dest)