Esempio n. 1
0
def write_svg(dataset, name, scale=1, img=True):
    '''write_svg(Options dataset, str name, num scale) -> SVG'''

    if 'size' in dataset:
        shape = dataset.size
    else: shape = png_to_ndarray(dataset.fname).shape

    shb = builders.ShapeBuilder()
    out = builders.svg(name)
    img = builders.image(x=0, y=0, width=shape[1], height=shape[0])
    img.set_xlink_href(os.path.abspath(dataset.fname))
    grp = builders.g()
    grp.set_transform("scale(%f, %f)" % tuple(scale * np.array(dataset.aspect)))
    grp.addElement(img)
    out.addElement(grp)
    return out
Esempio n. 2
0
 def create(self):
     path = '/home/max/workspace/SnakeIsland/resources/images/svgexport'
     self.setPath(path)
     vigra.impex.writeImage(self.image, self.imgpath)
     self.svgdoc = svg()
     # add image
     svgimg = svgimage(x=0,y=0,height=1000,width=1000)
     svgimg.set_xlink_href(self.imgpath)
     self.svgdoc.addElement(svgimg)
     # draw mapfeatures
     self.drawMapFeatures(self.mapfeatures)
     # draw snakes
     green = 'lime'
     red = 'red'
     self.drawSnake(self.refsnk, colour=red)
     self.drawSnake(self.optsnk, colour=green)
Esempio n. 3
0
    def draw(self):

        #TODO:place testgrid 1" to the right of the TitleBlock

        # the user may have specified on the command line to draw groups that
        # aren't present in the file. If not present, print a warning and remove those groups from the self.displayed_groups list.
        todelete = []
        for gpname in self.displayed_groups:
            if gpname not in self.groups:
                print 'Warning: Command line printgroups argument included group <%s> but that group is not in the pattern' % gpname
                todelete.append(gpname)
        for delgrp in todelete:
            self.displayed_groups.remove(delgrp)

        # any sanity checks on configuration before drawing go here
        if 'border' not in self.cfg:
            self.cfg['border'] = 2.54 * CM_TO_PX

        # if there are no groups in the list of ones to draw, then default to all of them
        if len(self.displayed_groups) == 0:
            for groupname in self.groups:
                self.displayed_groups.append(groupname)

        # create the base pysvg object
        svg_base = PYB.svg()

        if 'tooltips' in self.cfg:
            # If --tooltips specified in mkpattern command line options
            # create pysvg script class object, add to svg_base object, & set script to initialize on document load
            svg_script = PYB.script()
            svg_script.set_xlink_href('tmtp_mouse.js')
            svg_script.set_xlink_type('text/ecmascript')
            svg_base.addElement(svg_script)
            svg_base.set_onload('init(evt)')

            # Add the tooltip text element. Start it hidden at upper left with 'ToolTip' as it's displayable string.
            ttel = self.generateText(0, 0, 'tooltip', 'ToolTip',
                                     'tooltip_text_style')
            ttel.setAttribute('visibility', 'hidden')
            svg_base.addElement(ttel)

        # for some of the common information, make them attributes also
        meta_info = self.cfg['metainfo']
        for lbl in [
                'companyName', 'designerName', 'patternname', 'patternNumber'
        ]:
            if lbl in meta_info:
                self.attrs[lbl] = meta_info[
                    lbl]  # adds the self.cfg metainfo dictionary items to self.attrs so they will be written to the svg document.

        self.attrs['client-name'] = self.cfg[
            'clientdata'].customername  # Add customername to self.attrs so it can be written to the svg document.

        # Writes border values to the svg document, in case they were adjusted in self.cfg[] in the design
        self.attrs['margin-bottom'] = str(self.cfg['border'])
        self.attrs['margin-left'] = str(self.cfg['border'])
        self.attrs['margin-right'] = str(self.cfg['border'])
        self.attrs['margin-top'] = str(self.cfg['border'])

        # Add namespaces
        if 'noinkscape' not in self.cfg:
            self.attrs[
                'xmlns:inkscape'] = 'http://www.inkscape.org/namespaces/inkscape'

        # Add attributes - TODO probably put these in a dictionary as
        # part of the document class
        if self.attrs:
            for attr, value in self.attrs.items():
                svg_base.setAttribute(attr, value)
        svg_base.setAttribute(
            'xmlns:sodipodi',
            'http://inkscape.sourceforge.net/DTD/sodipodi-0.dtd')

        # //svg:svg/sodipodi:namedspace/inkscape:document-units
        svg_base.appendTextContent("""<sodipodi:namedview
             id="base"
             pagecolor="#ffffff"
             bordercolor="#666666"
             borderopacity="1.0"
             inkscape:pageopacity="0.0"
             inkscape:pageshadow="2"
             inkscape:zoom="0.5"
             inkscape:document-units="pt"
             showgrid="false"
             inkscape:window-maximized="1" />\n""")

        # If any markers used, add marker definitions to the svg document so they can be referenced within the svg document
        # two types of markers -- plain is a string, dictionary has more than one marker
        # each marker has a start & end, with optional mid
        if len(self.markers):
            pdefs = PYB.defs()  # Create pysvg builder defs class object
            for mname in self.markers:
                #print 'Adding marker %s' % mname
                if type(self.markerdefs[mname]) is str:
                    # this is just a plain marker, append it
                    pdefs.appendTextContent(
                        self.markerdefs[mname])  # append marker def to pdfs[]
                elif type(self.markerdefs[mname]) is dict:
                    # contains a dict of marks
                    for submrk in self.markerdefs[
                            mname]:  # append each marker in the marker dictionary to pdefs[]
                        # always has start and end, may also have mid
                        pdefs.appendTextContent(self.markerdefs[mname][submrk])
                else:
                    print mname, 'marker is an unexpected type ***************'

            svg_base.addElement(pdefs)  # write pdefs to pysvg base object

        # Recursively get everything to draw. svgdict[] will contain everything that will be written to the svg document.
        svgdict = self.getsvg()

        # Add/modify the transform so that the whole pattern piece originates at 0,0 and is offset by border
        xlo, ylo, xhi, yhi = self.boundingBox()
        xtrans = (-1.0 * xlo) + self.cfg['border']
        ytrans = (-1.0 * ylo) + self.cfg['border']
        fixuptransform = ('translate(%f,%f)' % (xtrans, ytrans))

        # -spc- TODO This is clearly wrong - it sizes the document to the pattern and ignores paper size
        xsize = (xhi - xlo) + (2.0 * self.cfg['border']) + SEAM_ALLOWANCE
        ysize = (yhi - ylo) + (2.0 * self.cfg['border']) + SEAM_ALLOWANCE
        svg_base.set_height(ysize)
        svg_base.set_width(xsize)
        #print 'document height = ', ysize
        #print 'document width = ', xsize

        for dictname, dictelements in svgdict.items():
            if self.debug:
                print 'processing group %s for output' % dictname
            if dictname not in self.displayed_groups:
                if self.debug:
                    print 'Group %s is not enabled for display' % dictname
                continue

            svg_group = PYB.g()
            self.groups[dictname] = svg_group
            # Set the ID to the group name
            svg_group.set_id(dictname)

            # set the transform in each group
            svg_group.setAttribute('transform', fixuptransform)
            if 'noinkscape' not in self.cfg:
                # add inkscape layer attributes
                svg_group.setAttribute('inkscape:groupmode', 'layer')
                svg_group.setAttribute('inkscape:label',
                                       ('Label-%s' % dictname))

            # Now add all the elements to it
            for svgel in dictelements:
                svg_group.addElement(svgel)

            # Now add the top level group to the document
            svg_base.addElement(svg_group)

        # Write out the svg file
        svg_base.save(self.filename)
        return
Esempio n. 4
0
    MAXWIDTH = 3
    #values = [20000., 24800., 30000.]
    values = map(float, [20000, 32000, 35000, 40000])
    colors = { 20000. : hsl2rgb(60,50,55), 
            28000. : hsl2rgb(120,50,50),
            29000. : hsl2rgb(180,50,50)}
    gm = grad_mag(png_to_ndarray(dataset.fname), dataset.aspect)
    gm_scale = 1. / gm.max()
    def f(line, val, (i,j)):
        width = gm[i:i+2,j:j+2].sum() * gm_scale / 4 * MAXWIDTH
        color = hsl2rgb(60 if val < 30000 else 240, width * 100/MAXWIDTH, 50)
        return make_line(line, color=color, width=width)
        #return make_line(line, color=colors[val], width=0 + gm[i:i+2,j:j+2].sum()**2 * gm_scale)

    if not os.path.exists(saveas): os.mkdir(saveas)
    svg = builders.svg('feeth-lines')
    for line in param_isocontours(dataset, values, f):
        svg.addElement(line)
    svg.save(saveas + 'feeth-lines.svg')

def part2e(dataset=images.tooth, values=None, saveas="output/part2e/"):
    #values = list(np.hstack((np.linspace(0,5000,num=3), np.array([15000]), np.linspace(38000,42000, num=1), np.linspace(60000,63000,num=2))))
    values = map(float, [15000, 38000, 42000, 60000]) # 42000, 
    WHITE = hsl2rgb(0, 0, 100)
    YELLOW = hsl2rgb(60, 75, 70)
    RED = hsl2rgb(0,50,50)
    def f(line, val, (i,j)):
        return make_line(line, color=WHITE if val > 45000 else YELLOW if val > 20000 else RED, width=2 if val != 42000 else 1)

    if not os.path.exists(saveas): os.mkdir(saveas)
    Image.fromarray(np.zeros((161,94), dtype='int32'), mode='I').save(saveas + 'solid-bg.png')