Python svgwrite.Drawing() Examples

The following are 30 code examples for showing how to use svgwrite.Drawing(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module svgwrite , or try the search function .

Example 1
Project: giftolottie   Author: bodqhrohro   File: svg.py    License: MIT License 6 votes vote down vote up
def save(shapes, name):
    svg = svgwrite.Drawing(filename = name, size = ("512px", "512px"))

    for shape in shapes:
        if shape['type'] == 'rect':
            svg.add(svg.rect(
                insert = (str(shape['coords'][0][0]) + "px", str(shape['coords'][0][1]) + "px"),
                size = (
                    str(shape['coords'][1][0] - shape['coords'][0][0]) + "px",
                    str(shape['coords'][1][1] - shape['coords'][0][1]) + "px",
                ),
                #stroke_width = "0",
                fill = "rgb(" + ",".join(map(str, shape['color'])) + ")"
            ))

    svg.save() 
Example 2
Project: GpxTrackPoster   Author: flopp   File: circular_drawer.py    License: MIT License 6 votes vote down vote up
def _draw_rings(self, dr: svgwrite.Drawing, center: XY, radius_range: ValueRange):
        length_range = self.poster.length_range_by_date
        ring_distance = self._determine_ring_distance()
        if ring_distance is None:
            return
        distance = ring_distance
        while distance < length_range.upper():
            radius = (
                radius_range.lower()
                + radius_range.diameter() * distance / length_range.upper()
            )
            dr.add(
                dr.circle(
                    center=center.tuple(),
                    r=radius,
                    stroke=self._ring_color,
                    stroke_opacity="0.2",
                    fill="none",
                    stroke_width=0.3,
                )
            )
            distance += ring_distance 
Example 3
Project: GpxTrackPoster   Author: flopp   File: heatmap_drawer.py    License: MIT License 6 votes vote down vote up
def draw(self, dr: svgwrite.Drawing, size: XY, offset: XY):
        """Draw the heatmap based on tracks."""
        bbox = self._determine_bbox()
        for tr in self.poster.tracks:
            color = self.color(self.poster.length_range, tr.length, tr.special)
            for line in utils.project(bbox, size, offset, tr.polylines):
                for opacity, width in [(0.1, 5.0), (0.2, 2.0), (1.0, 0.3)]:
                    dr.add(
                        dr.polyline(
                            points=line,
                            stroke=color,
                            stroke_opacity=opacity,
                            fill="none",
                            stroke_width=width,
                            stroke_linejoin="round",
                            stroke_linecap="round",
                        )
                    ) 
Example 4
Project: GpxTrackPoster   Author: flopp   File: calendar_drawer.py    License: MIT License 6 votes vote down vote up
def draw(self, dr: svgwrite.Drawing, size: XY, offset: XY):
        """Iterate through the Poster's years, creating a calendar for each."""
        if self.poster.tracks is None:
            raise PosterError("No tracks to draw.")
        years = self.poster.years.count()
        _, counts = utils.compute_grid(years, size)
        if counts is None:
            raise PosterError("Unable to compute grid.")
        count_x, count_y = counts[0], counts[1]
        x, y = 0, 0
        cell_size = size * XY(1 / count_x, 1 / count_y)
        margin = XY(4, 8)
        if count_x <= 1:
            margin.x = 0
        if count_y <= 1:
            margin.y = 0
        sub_size = cell_size - 2 * margin

        for year in range(self.poster.years.from_year, self.poster.years.to_year + 1):
            self._draw(dr, sub_size, offset + margin + cell_size * XY(x, y), year)
            x += 1
            if x >= count_x:
                x = 0
                y += 1 
Example 5
Project: doom-net-pytorch   Author: akolishchak   File: wad.py    License: MIT License 6 votes vote down vote up
def save_svg(self):
        """ Scale the drawing to fit inside a 1024x1024 canvas (iPhones don't like really large SVGs even if they have the same detail) """
        import svgwrite
        view_box_size = self.normalize(self.upper_right, 10)
        if view_box_size[0] > view_box_size[1]:
            canvas_size = (1024, int(1024 * (float(view_box_size[1]) / view_box_size[0])))
        else:
            canvas_size = (int(1024 * (float(view_box_size[0]) / view_box_size[1])), 1024)

        dwg = svgwrite.Drawing(self.name + '.svg', profile='tiny', size=canvas_size,
                               viewBox=('0 0 %d %d' % view_box_size))
        for line in self.lines:
            a = self.normalize(self.vertices[line.a])
            b = self.normalize(self.vertices[line.b])
            if line.is_one_sided():
                dwg.add(dwg.line(a, b, stroke='#333', stroke_width=10))
            else:
                dwg.add(dwg.line(a, b, stroke='#999', stroke_width=3))

        dwg.save() 
Example 6
Project: python-fretboard   Author: dmpayton   File: fretboard.py    License: MIT License 6 votes vote down vote up
def draw(self):
        self.drawing = svgwrite.Drawing(size=(
            self.style.drawing.width,
            self.style.drawing.height
        ))

        if self.style.drawing.background_color is not None:
            self.drawing.add(
                self.drawing.rect(
                    insert=(0, 0),
                    size=(
                        self.style.drawing.width,
                        self.style.drawing.height
                    ),
                    fill=self.style.drawing.background_color
                )
            )

        self.calculate_layout()
        self.draw_frets()
        self.draw_inlays()
        self.draw_fret_label()
        self.draw_strings()
        self.draw_nut()
        self.draw_markers() 
Example 7
Project: databench   Author: svenkreiss   File: create.py    License: MIT License 6 votes vote down vote up
def main():
    svg_favicon = svgwrite.Drawing(filename="favicon.svg",
                                   size=("128px", "128px"))
    svg_document = svgwrite.Drawing(filename="logo.svg",
                                    size=("128px", "128px"))
    for y, r in enumerate(DATA):
        for x, v in enumerate(r):
            simple(svg_favicon, x, y, v)
            smaller(svg_document, x, y, v)
    print(svg_document.tostring())
    svg_favicon.save()
    svg_document.save()

    # create pngs
    os.system('svg2png logo.svg --width=100 --height=100')
    os.system('svg2png logo.svg --width=600 --height=600')
    favicon_sizes = [16, 32, 48, 128, 256]
    for s in favicon_sizes:
        os.system('svg2png favicon.svg --width='+str(s)+' --height='+str(s))
    png_favicon_names = ['favicon-w'+str(s)+'.png' for s in favicon_sizes]
    os.system('convert ' + (' '.join(png_favicon_names)) +
              ' -colors 256 favicon.ico') 
Example 8
Project: examples-camera   Author: google-coral   File: detect.py    License: Apache License 2.0 6 votes vote down vote up
def generate_svg(src_size, inference_size, inference_box, objs, labels, text_lines):
    dwg = svgwrite.Drawing('', size=src_size)
    src_w, src_h = src_size
    inf_w, inf_h = inference_size
    box_x, box_y, box_w, box_h = inference_box
    scale_x, scale_y = src_w / box_w, src_h / box_h

    for y, line in enumerate(text_lines, start=1):
        shadow_text(dwg, 10, y*20, line)
    for obj in objs:
        x0, y0, x1, y1 = list(obj.bbox)
        # Relative coordinates.
        x, y, w, h = x0, y0, x1 - x0, y1 - y0
        # Absolute coordinates, input tensor space.
        x, y, w, h = int(x * inf_w), int(y * inf_h), int(w * inf_w), int(h * inf_h)
        # Subtract boxing offset.
        x, y = x - box_x, y - box_y
        # Scale to source coordinate space.
        x, y, w, h = x * scale_x, y * scale_y, w * scale_x, h * scale_y
        percent = int(100 * obj.score)
        label = '{}% {}'.format(percent, labels.get(obj.id, obj.id))
        shadow_text(dwg, x, y - 5, label)
        dwg.add(dwg.rect(insert=(x,y), size=(w, h),
                        fill='none', stroke='red', stroke_width='2'))
    return dwg.tostring() 
Example 9
Project: brand   Author: phodal   File: basic.py    License: Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def generate_works():
    dwg = svgwrite.Drawing('generate/basic.svg', size=(u'1200', u'600'))

    shapes = dwg.add(dwg.g(id='shapes', fill='none'))

    for x in range(1, 150):
        shapes.add(dwg.line((250, 60 + x), (380, 0 + x), stroke='#59B840', stroke_width=1))

    for x in range(1, 150):
        shapes.add(dwg.line((380, 0 + x), (420, 60 + x), stroke='#1A7906', stroke_width=1))

    # color bg: #1A7906

    shapes.add(dwg.rect((420, 60), (950, 250), fill='#59B840'))

    shapes.add(dwg.text('标题', insert=(450, 240), fill='#fff', font_size=160,
                        font_family='Helvetica'))
    shapes.add(dwg.line((440, 280), (1180, 280), stroke='#fff', stroke_width=4))

    dwg.save() 
Example 10
Project: tsinfer   Author: tskit-dev   File: visualisation.py    License: GNU General Public License v3.0 5 votes vote down vote up
def draw(self, ancestor_id, filename_pattern):
        start = self.ancestor_data.ancestors_start[ancestor_id]
        end = self.ancestor_data.ancestors_end[ancestor_id]
        focal_sites = self.ancestor_data.ancestors_focal_sites[ancestor_id]
        a = np.zeros(self.sample_data.num_sites, dtype=int)
        a[:] = -1
        a[start:end] = self.ancestor_data.ancestors_haplotype[ancestor_id]
        print(start, end, focal_sites, a)

        dwg = svgwrite.Drawing(size=(self.width, self.height), debug=True)
        self.draw_matrix(dwg, focal_sites, a)
        with open(filename_pattern.format(0), "w") as f:
            f.write(dwg.tostring()) 
Example 11
Project: project-posenet   Author: google-coral   File: anonymizer.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    background_locked = False
    timer_time = time.monotonic()

    def run_inference(engine, input_tensor):
        return engine.run_inference(input_tensor)

    def render_overlay(engine, output, src_size, inference_box):
        nonlocal timer_time, background_locked
        svg_canvas = svgwrite.Drawing('', size=src_size)
        outputs, inference_time = engine.ParseOutput(output)
        now_time = time.monotonic()

        if not background_locked:
            print('Waiting for everyone to leave the frame...')
            pose_camera.shadow_text(svg_canvas, 10, 20,
                                    'Waiting for everyone to leave the frame...')
            if outputs:  # frame still has people in it, restart timer
                timer_time = now_time
            elif now_time > timer_time + BACKGROUND_DELAY:  # frame has been empty long enough
                background_locked = True
                print('Background set.')

        for pose in outputs:
            pose_camera.draw_pose(svg_canvas, pose, src_size, inference_box)

        return (svg_canvas.tostring(), background_locked)

    pose_camera.run(run_inference, render_overlay) 
Example 12
Project: project-posenet   Author: google-coral   File: pose_camera.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    n = 0
    sum_process_time = 0
    sum_inference_time = 0
    ctr = 0
    fps_counter  = avg_fps_counter(30)

    def run_inference(engine, input_tensor):
        return engine.run_inference(input_tensor)

    def render_overlay(engine, output, src_size, inference_box):
        nonlocal n, sum_process_time, sum_inference_time, fps_counter

        svg_canvas = svgwrite.Drawing('', size=src_size)
        start_time = time.monotonic()
        outputs, inference_time = engine.ParseOutput(output)
        end_time = time.monotonic()
        n += 1
        sum_process_time += 1000 * (end_time - start_time)
        sum_inference_time += inference_time

        avg_inference_time = sum_inference_time / n
        text_line = 'PoseNet: %.1fms (%.2f fps) TrueFPS: %.2f Nposes %d' % (
            avg_inference_time, 1000 / avg_inference_time, next(fps_counter), len(outputs)
        )

        shadow_text(svg_canvas, 10, 20, text_line)
        for pose in outputs:
            draw_pose(svg_canvas, pose, src_size, inference_box)
        return (svg_canvas.tostring(), False)

    run(run_inference, render_overlay) 
Example 13
Project: Timeline   Author: jasonreisman   File: make_timeline.py    License: MIT License 5 votes vote down vote up
def __init__(self, filename):
		# load timeline data
		s = ''
		with open(filename) as f:
			s = f.read()
		self.data = json.loads(s)
		assert 'width' in self.data, 'width property must be set'
		assert 'start' in self.data, 'start property must be set'
		assert 'end' in self.data, 'end property must be set'
		# create drawing
		self.width = self.data['width']
		self.drawing = svgwrite.Drawing()
		self.drawing['width'] = self.width
		self.g_axis = self.drawing.g()		
		# figure out timeline boundaries
		self.cal = parsedatetime.Calendar()
		self.start_date = self.datetime_from_string(self.data['start'])
		self.end_date = self.datetime_from_string(self.data['end'])
		delta = self.end_date[0] - self.start_date[0]
		padding = datetime.timedelta(seconds=0.1*delta.total_seconds())
		self.date0 = self.start_date[0] - padding
		self.date1 = self.end_date[0] + padding
		self.total_secs = (self.date1 - self.date0).total_seconds()	
		# set up some params
		self.callout_size = (10, 15, 10) # width, height, increment
		self.text_fudge = (3, 1.5)
		self.tick_format = self.data.get('tick_format', None)
		self.markers = {}
		# initialize Tk so that font metrics will work
		self.tk_root = Tkinter.Tk()
		self.fonts = {}
		# max_label_height stores the max height of all axis labels
		# and is used in the final height computation in build(self)
		self.max_label_height = 0 
Example 14
Project: GpxTrackPoster   Author: flopp   File: poster.py    License: MIT License 5 votes vote down vote up
def draw(self, drawer, output):
        """Set the Poster's drawer and draw the tracks."""
        self.tracks_drawer = drawer
        d = svgwrite.Drawing(output, (f"{self.width}mm", f"{self.height}mm"))
        d.viewbox(0, 0, self.width, self.height)
        d.add(d.rect((0, 0), (self.width, self.height), fill=self.colors["background"]))
        self.__draw_header(d)
        self.__draw_footer(d)
        self.__draw_tracks(d, XY(self.width - 20, self.height - 30 - 30), XY(10, 30))
        d.save() 
Example 15
Project: GpxTrackPoster   Author: flopp   File: circular_drawer.py    License: MIT License 5 votes vote down vote up
def draw(self, dr: svgwrite.Drawing, size: XY, offset: XY):
        """Draw the circular Poster using distances broken down by time"""
        if self.poster.tracks is None:
            raise PosterError("No tracks to draw.")
        if self.poster.length_range_by_date is None:
            return

        years = self.poster.years.count()
        _, counts = utils.compute_grid(years, size)
        if counts is None:
            raise PosterError("Unable to compute grid.")
        count_x, count_y = counts[0], counts[1]
        x, y = 0, 0
        cell_size = size * XY(1 / count_x, 1 / count_y)
        margin = XY(4, 4)
        if count_x <= 1:
            margin.x = 0
        if count_y <= 1:
            margin.y = 0
        sub_size = cell_size - 2 * margin
        for year in range(self.poster.years.from_year, self.poster.years.to_year + 1):
            self._draw_year(dr, sub_size, offset + margin + cell_size * XY(x, y), year)
            x += 1
            if x >= count_x:
                x = 0
                y += 1 
Example 16
Project: GpxTrackPoster   Author: flopp   File: circular_drawer.py    License: MIT License 5 votes vote down vote up
def _draw_circle_segment(
        self,
        dr: svgwrite.Drawing,
        tracks: List[Track],
        a1: float,
        a2: float,
        rr: ValueRange,
        center: XY,
    ):
        length = sum([t.length for t in tracks])
        has_special = len([t for t in tracks if t.special]) > 0
        color = self.color(self.poster.length_range_by_date, length, has_special)
        r1 = rr.lower()
        r2 = (
            rr.lower()
            + rr.diameter() * length / self.poster.length_range_by_date.upper()
        )
        sin_a1, cos_a1 = math.sin(a1), math.cos(a1)
        sin_a2, cos_a2 = math.sin(a2), math.cos(a2)
        path = dr.path(
            d=("M", center.x + r1 * sin_a1, center.y - r1 * cos_a1),
            fill=color,
            stroke="none",
        )
        path.push("l", (r2 - r1) * sin_a1, (r1 - r2) * cos_a1)
        path.push(f"a{r2},{r2} 0 0,0 {r2 * (sin_a2 - sin_a1)},{r2 * (cos_a1 - cos_a2)}")
        path.push("l", (r1 - r2) * sin_a2, (r2 - r1) * cos_a2)
        dr.add(path) 
Example 17
Project: GpxTrackPoster   Author: flopp   File: grid_drawer.py    License: MIT License 5 votes vote down vote up
def draw(self, dr: svgwrite.Drawing, size: XY, offset: XY):
        """For each track, draw it on the poster."""
        if self.poster.tracks is None:
            raise PosterError("No tracks to draw.")
        cell_size, counts = utils.compute_grid(len(self.poster.tracks), size)
        if cell_size is None or counts is None:
            raise PosterError("Unable to compute grid.")
        count_x, count_y = counts[0], counts[1]
        spacing_x = (
            0 if count_x <= 1 else (size.x - cell_size * count_x) / (count_x - 1)
        )
        spacing_y = (
            0 if count_y <= 1 else (size.y - cell_size * count_y) / (count_y - 1)
        )
        offset.x += (size.x - count_x * cell_size - (count_x - 1) * spacing_x) / 2
        offset.y += (size.y - count_y * cell_size - (count_y - 1) * spacing_y) / 2
        for (index, tr) in enumerate(self.poster.tracks):
            p = XY(index % count_x, index // count_x) * XY(
                cell_size + spacing_x, cell_size + spacing_y
            )
            self._draw_track(
                dr,
                tr,
                0.9 * XY(cell_size, cell_size),
                offset + 0.05 * XY(cell_size, cell_size) + p,
            ) 
Example 18
Project: GpxTrackPoster   Author: flopp   File: tracks_drawer.py    License: MIT License 5 votes vote down vote up
def draw(self, dr: svgwrite.Drawing, size: XY, offset: XY):
        pass 
Example 19
Project: anki-maobi   Author: jcklie   File: generate_hanzi_grids.py    License: MIT License 5 votes vote down vote up
def field():
    dwg = svgwrite.Drawing('maobi/field.svg', profile='tiny', size=(SIZE, SIZE))
    dwg.add(dwg.line((SIZE / 2, 0), (SIZE / 2, SIZE), stroke=GRID_COLOR, stroke_width=GRID_STROKE_WIDTH))
    dwg.add(dwg.line((0, SIZE / 2), (SIZE, SIZE / 2), stroke=GRID_COLOR, stroke_width=GRID_STROKE_WIDTH))

    dwg.save() 
Example 20
Project: anki-maobi   Author: jcklie   File: generate_hanzi_grids.py    License: MIT License 5 votes vote down vote up
def rice():
    o = GRID_STROKE_WIDTH / 2
    dwg = svgwrite.Drawing('maobi/rice.svg', profile='tiny', size=(SIZE, SIZE))
    dwg.add(dwg.line((o, o), (SIZE - o, SIZE - o), stroke=GRID_COLOR, stroke_width=GRID_STROKE_WIDTH))
    dwg.add(dwg.line((o, SIZE - o), (SIZE - o, o), stroke=GRID_COLOR, stroke_width=GRID_STROKE_WIDTH))
    dwg.add(dwg.line((SIZE / 2, 0), (SIZE / 2, SIZE), stroke=GRID_COLOR, stroke_width=GRID_STROKE_WIDTH))
    dwg.add(dwg.line((0, SIZE / 2), (SIZE, SIZE / 2), stroke=GRID_COLOR, stroke_width=GRID_STROKE_WIDTH))

    dwg.save() 
Example 21
Project: incremental-sequence-learning   Author: edwin-de-jong   File: utils.py    License: MIT License 5 votes vote down vote up
def draw_strokes( data, factor = 10, svg_filename = 'sample.svg' ):
  min_x, max_x, min_y, max_y = get_bounds( data, factor )
  dims = ( 50 + max_x - min_x, 50 + max_y - min_y )
    
  dwg = svgwrite.Drawing( svg_filename, size = dims )
  dwg.add( dwg.rect( insert = ( 0, 0 ), size = dims, fill = 'white' ) )

  lift_pen = 1
    
  abs_x = 25 - min_x 
  abs_y = 25 - min_y
  p = "M%s, %s " % ( abs_x, abs_y )
    
  command = "m"

  for i in range( len( data ) ):
    if ( lift_pen == 1 ):
      command = "m"
    elif ( command != "l" ):
      command = "l"
    else:
      command = ""
    x = float( data[ i, 0 ] )/factor
    y = float( data[ i, 1 ] )/factor
    lift_pen = data[ i, 2 ]
    p += command+str( x )+", "+str( y )+" "

  the_color = "black"
  stroke_width = 1

  dwg.add( dwg.path( p ).stroke( the_color, stroke_width ).fill( "none" ) )

  dwg.save( )
  display( SVG( dwg.tostring( ) ) ) 
Example 22
Project: incremental-sequence-learning   Author: edwin-de-jong   File: utils.py    License: MIT License 5 votes vote down vote up
def draw_strokes_custom_color( data, factor = 10, svg_filename = 'test.svg', color_data = None, stroke_width = 1 ):
  min_x, max_x, min_y, max_y = get_bounds( data, factor )
  dims = ( 50 + max_x - min_x, 50 + max_y - min_y )
    
  dwg = svgwrite.Drawing( svg_filename, size = dims )
  dwg.add( dwg.rect( insert = ( 0, 0 ), size = dims, fill = 'white' ) )

  lift_pen = 1
  abs_x = 25 - min_x 
  abs_y = 25 - min_y

  for i in range( len( data ) ):

    x = float( data[ i, 0 ] )/factor
    y = float( data[ i, 1 ] )/factor

    prev_x = abs_x
    prev_y = abs_y

    abs_x += x
    abs_y += y

    if ( lift_pen == 1 ):
      p = "M "+str( abs_x )+", "+str( abs_y )+" "
    else:
      p = "M +"+str( prev_x )+", "+str( prev_y )+" L "+str( abs_x )+", "+str( abs_y )+" "

    lift_pen = data[ i, 2 ]

    the_color = "black"

    if ( color_data is not None ):
      the_color = "rgb( "+str( int( color_data[ i, 0 ] ) )+", "+str( int( color_data[ i, 1 ] ) )+", "+str( int( color_data[ i, 2 ] ) )+" )"

    dwg.add( dwg.path( p ).stroke( the_color, stroke_width ).fill( the_color ) )
  dwg.save( )
  display( SVG( dwg.tostring( ) ) ) 
Example 23
Project: incremental-sequence-learning   Author: edwin-de-jong   File: utils.py    License: MIT License 5 votes vote down vote up
def draw_strokes_pdf( data, param, factor = 10, svg_filename = 'sample_pdf.svg' ):
  min_x, max_x, min_y, max_y = get_bounds( data, factor )
  dims = ( 50 + max_x - min_x, 50 + max_y - min_y )

  dwg = svgwrite.Drawing( svg_filename, size = dims )
  dwg.add( dwg.rect( insert = ( 0, 0 ), size = dims, fill = 'white' ) )

  abs_x = 25 - min_x 
  abs_y = 25 - min_y

  num_mixture = len( param[ 0 ][ 0 ] )

  for i in range( len( data ) ):

    x = float( data[ i, 0 ] )/factor
    y = float( data[ i, 1 ] )/factor

    for k in range( num_mixture ):
      pi = param[ i ][ 0 ][ k ]
      if pi > 0.01: # optimisation, ignore pi's less than 1% chance
        mu1 = param[ i ][ 1 ][ k ]
        mu2 = param[ i ][ 2 ][ k ]
        s1 = param[ i ][ 3 ][ k ]
        s2 = param[ i ][ 4 ][ k ]
        sigma = np.sqrt( s1*s2 )
        dwg.add( dwg.circle( center = ( abs_x+mu1*factor, abs_y+mu2*factor ), r = int( sigma*factor ) ).fill( 'red', opacity = pi/( sigma*sigma*factor ) ) )

    prev_x = abs_x
    prev_y = abs_y

    abs_x += x
    abs_y += y


  dwg.save( )
  display( SVG( dwg.tostring( ) ) ) 
Example 24
Project: tskit   Author: tskit-dev   File: drawing.py    License: MIT License 5 votes vote down vote up
def setup_drawing(self):
        "Return an svgwrite.Drawing object for further use"
        dwg = svgwrite.Drawing(
            size=self.image_size, debug=True, **self.root_svg_attributes
        )
        dwg.defs.add(dwg.style(self.standard_style))
        tree_class = f"tree t{self.tree.index}"
        self.root_group = dwg.add(dwg.g(class_=tree_class))
        return dwg 
Example 25
Project: psd2svg   Author: kyamagu   File: __init__.py    License: MIT License 5 votes vote down vote up
def convert(self, layer, output=None):
        """Convert the given PSD to SVG."""
        self.reset()
        self._set_input(layer)
        self._set_output(output)

        layer = self._layer
        bbox = layer.viewbox if hasattr(layer, 'viewbox') else layer.bbox
        if bbox == (0, 0, 0, 0):
            bbox = self._psd.viewbox

        self._dwg = svgwrite.Drawing(
            size=(bbox[2] - bbox[0], bbox[3] - bbox[1]),
            viewBox='%d %d %d %d' % (
                bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]
            ),
        )
        if layer.is_group():
            self.create_group(layer, self._dwg)
        else:
            self._dwg.add(self.convert_layer(layer))

        # Layerless PSDImage.
        if (
            isinstance(layer, PSDImage) and len(layer) == 0 and
            layer.has_preview()
        ):
            self._dwg.add(self._dwg.image(
                self._get_image_href(layer.topil()),
                insert=(0, 0),
                size=(layer.width, layer.height),
                debug=False
            ))
        return self._save_svg() 
Example 26
Project: project-teachable   Author: google-coral   File: gstreamer.py    License: Apache License 2.0 5 votes vote down vote up
def on_new_sample(sink, overlay, screen_size, appsink_size, user_function):
    sample = sink.emit('pull-sample')
    buf = sample.get_buffer()
    result, mapinfo = buf.map(Gst.MapFlags.READ)
    if result:
      img = Image.frombytes('RGB', (appsink_size[0], appsink_size[1]), mapinfo.data, 'raw')
      svg_canvas = svgwrite.Drawing('', size=(screen_size[0], screen_size[1]))
      user_function(img, svg_canvas)
      overlay.set_property('data', svg_canvas.tostring())
    buf.unmap(mapinfo)
    return Gst.FlowReturn.OK 
Example 27
Project: touchdesigner-sop-to-svg   Author: raganmd   File: svgEXT.py    License: MIT License 5 votes vote down vote up
def SavePolyline(self, path, pline):
		''' This is a sample method.

		This sample method is intended to help illustrate what method docstrings should look like.
						
		Notes
		---------------
		'self' does not need to be included in the Args section.

		Args
		---------------
		name (str): A string name, with spaces as underscores
		age (int): Age as full year measurements
		height (float): Height in meters to 2 significant digits, ex: 1.45

		Examples
		---------------

		Returns
		---------------
		formatted_profile (str) : A formatted string populated with the with the supplied information
		'''
		Canvassize 		= self.Canvas_size()

		prims 			= pline.prims
		dwg 			= svgwrite.Drawing(path, profile='tiny', size=Canvassize)

		for item in prims:
			
			if self.UseCamera:
				newPoints 	= [self.WorldToCam(vert.point.P) for vert in item ]
			else:
				newPoints 	= [(vert.point.x,vert.point.y) for vert in item ]
			
			newPoly		= dwg.polyline(points=newPoints, stroke='black', stroke_width=1, fill='none')
			dwg.add(newPoly)

		dwg.save()

		return 
Example 28
Project: touchdesigner-sop-to-svg   Author: raganmd   File: svgEXT.py    License: MIT License 5 votes vote down vote up
def SavePolygon(self, path, pgon):
		''' This is a sample method.

		This sample method is intended to help illustrate what method docstrings should look like.
						
		Notes
		---------------
		'self' does not need to be included in the Args section.

		Args
		---------------
		name (str): A string name, with spaces as underscores
		age (int): Age as full year measurements
		height (float): Height in meters to 2 significant digits, ex: 1.45

		Examples
		---------------

		Returns
		---------------
		formatted_profile (str) : A formatted string populated with the with the supplied information
		'''
		Canvassize 		= self.Canvas_size()
	
		prims 			= pgon.prims
		dwg 			= svgwrite.Drawing(path, profile='tiny', size=Canvassize)

		for item in prims:
			
			if self.UseCamera:
				newPoints 	= [self.WorldToCam(vert.point.P) for vert in item ]
			else:
				newPoints 	= [(vert.point.x,vert.point.y) for vert in item ]

			newPoly		= dwg.polygon(points=newPoints, stroke='black', stroke_width=1, fill='none')
			dwg.add(newPoly)

		dwg.save() 
Example 29
Project: silhouette   Author: vishnubob   File: registration.py    License: MIT License 5 votes vote down vote up
def generate(self, svgfn="registration.svg"):
        svg = svgwrite.Drawing(svgfn)
        svg.add(self.cube_mark())
        svg.add(self.top_angle_mark())
        svg.add(self.bottom_angle_mark())
        svg.save() 
Example 30
Project: Pixel-Art   Author: vvanirudh   File: output.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_drawing(self, filename):
		return Drawing(filename)