Example #1
0
def multilayer_svg_as_string(paths):
    assert isinstance(paths, dict)

    def merge_layers(paths):
        out = []
        for layer_name, layer in paths.items():
            out.extend(layer)
        return out

    def layer_color(layer_name):
        return layer_name

    view_box = drawing_bbox(merge_layers(paths))
    svg_layers = []
    for layer_name, layer in paths.items():
        svg_paths = []
        for path in layer:
            svg_path = []
            for i in range(len(path)):
                pt = path[i]
                svg_path.append('{},{}'.format(pt[0], pt[1]))
            svg_path = ' '.join(svg_path)
            svg_paths.append('<polyline points="{}" />'.format(svg_path))
        svg_layer = '<g id="layer{}" style="fill:none;stroke:{}">\n{}\n</g>'.format(
            layer_name_to_id(layer_name), layer_color(layer_name),
            '\n'.join(svg_paths))
        svg_layers.append(svg_layer)
    document_params = 'version="1.1"\nxmlns="http://www.w3.org/2000/svg"'
    document_params += f'\nviewBox="{view_box[0]} {view_box[1]} {view_box[2]} {view_box[3]}"'
    document = '<svg {}>\n{}\n</svg>'.format(document_params,
                                             '\n'.join(svg_layers))
    # document = header + document
    return document
Example #2
0
def svg_as_string(paths):
    svg_paths = []
    view_box = drawing_bbox(paths)
    for path in paths:
        svg_path = []
        for i in range(len(path)):
            pt = path[i]
            svg_path.append('{},{}'.format(pt[0], pt[1]))
        svg_path = ' '.join(svg_path)
        svg_paths.append(
            '<polyline points="{}" style="fill:none;stroke:black;" />'.format(
                svg_path))
    # header = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n'
    document_params = 'version="1.1"\nxmlns="http://www.w3.org/2000/svg"'
    document_params += f'\nviewBox="{view_box[0]} {view_box[1]} {view_box[2]} {view_box[3]}"'
    document = '<svg {}>\n{}\n</svg>'.format(document_params,
                                             '\n'.join(svg_paths))
    # document = header + document
    return document
def run(args):
    N = 40
    size = 6
    # rot = 5
    # paths = rotate(hex_grid(N, N, size), np.radians(rot))
    N_rows = N
    N_cols = int(np.round(np.sqrt(2) * N))
    paths = hex_grid(N_rows, N_cols, size)
    paths_2 = hex_grid(N_rows, N_cols, size * (34 / 36))
    # paths_3 = rotate(
    #     hex_grid(N, N, size),
    #     np.radians(2 * rot)
    # )
    border = rounded_rect(drawing_bbox(paths_2), 15)
    paths = mask_drawing(paths, border)
    paths_2 = mask_drawing(paths_2, border)
    gui = Drawer()
    gui.add_lines(paths, 'k')
    gui.add_lines(paths_2, 'k')
    gui.draw()
    export_svg(paths + paths_2, '/tmp/hex_grids.svg')
    return 0
Example #4
0
def run(args):
    svg_path = args.path
    parsed_paths, attributes, svg_attributes = svgpt.svg2paths(
        svg_path, return_svg_attributes=True)
    logger.info('SVG loaded')

    paths = []
    for path in parsed_paths:
        if path.iscontinuous():
            paths.append(path)
        else:
            for p in path.continuous_subpaths():
                paths.append(p)

    np_paths = []
    step = 1
    for path_i, path in enumerate(tqdm.tqdm(paths, desc='paths')):
        np_path = [cplx_to_xy(path.start)]
        for part in path:
            if type(part) is svgpt.path.Line:
                start = cplx_to_xy(part.start)
                end = cplx_to_xy(part.end)
                if start != np_path[-1]:
                    np_path.append(start)
                np_path.append(end)
            else:
                length = part.length()
                steps = int(np.round(length / step))
                # steps = 20
                if steps == 0:
                    continue
                fraction_step = 1 / steps

                for i in range(steps + 1):
                    try:
                        pt = path.point(fraction_step * i)
                        pt = cplx_to_xy(pt)
                        np_path.append(pt)
                    except Exception:
                        pass

        np_paths.append(np.array(np_path))
    logger.info('SVG converted')

    to_draw = np_paths
    if args.rotate:
        to_draw = rotate(to_draw)

    page_conf = load_page_conf(args.format)

    x_margin_mm = args.margins
    y_margin_mm = args.margins
    H = page_conf['H']  # 210 # A4
    W = page_conf['W']  # 297 # A4

    to_draw = resize_and_center(to_draw, H, W, x_margin_mm, x_margin_mm,
                                y_margin_mm, y_margin_mm)
    orig = copy.deepcopy(to_draw)

    if args.border_crop:
        border = rounded_rect(drawing_bbox(to_draw), args.border_round)
        vis_drawing([border], 'b-', linewidth=0.5)

        logger.info("Masking drawing")
        to_draw = mask_drawing(to_draw, border)

    to_draw = multi_pass(to_draw, args.multipass)

    if not args.noopt:
        logger.info("Starting optimization")
        to_draw = optimize(to_draw,
                           path_join_threshold=args.join,
                           line_simplification_threshold=args.simplify,
                           path_drop_threshold=args.drop)

    logger.info('plotting')
    vis_drawing(to_draw, 'r-', linewidth=0.5)
    vis_drawing(orig, 'k-', linewidth=0.5)
    plt.plot([0, W, W, 0, 0], [0, 0, H, H, 0], 'k:')
    plt.axis('equal')
    # plt.gca().invert_yaxis()
    plt.show()

    with Plotter('/dev/ttyUSB0', 9600) as p:
        p.load_config(args.opconfig)
        p.set_input_limits((0, 0), (W, 0), (0, H), (W, H))
        p.set_speed(289)
        p.draw_polylines(to_draw)

    return 0
    def __init__(self,
                 lines=None,
                 line_colors=None,
                 lw=1,
                 points=None,
                 point_colors=None,
                 point_r=1):
        self.point_r = point_r
        # Configure to use pyglet window
        window_str = 'moderngl_window.context.pyglet.Window'
        window_cls = moderngl_window.get_window_cls(window_str)
        window = window_cls(
            title="My Window",
            gl_version=(3, 3),
            # aspect_ratio=1.0,
            # resizable=False,
            # size=(1600, 800),
        )
        self.wnd = window
        moderngl_window.activate_context(ctx=window.ctx)
        # self.wnd.gl_version = (3, 3)
        resources.register_dir(Path(__file__).parent.absolute())
        self.ctx = self.wnd.ctx

        # register event methods
        self.wnd.resize_func = self.resize
        # self.wnd.iconify_func = self.iconify
        # self.wnd.key_event_func = self.key_event
        # self.wnd.mouse_position_event_func = self.mouse_position_event
        # self.wnd.mouse_drag_event_func = self.mouse_drag_event
        # self.wnd.mouse_scroll_event_func = self.mouse_scroll_event
        # self.wnd.mouse_press_event_func = self.mouse_press_event
        # self.wnd.mouse_release_event_func = self.mouse_release_event
        # self.wnd.unicode_char_entered_func = self.unicode_char_entered

        self.line_prog = programs.load(
            ProgramDescription(path="rich_lines.glsl"))
        self.point_prog = programs.load(ProgramDescription(path="points.glsl"))

        bbox = drawing_bbox(lines + points)
        bbox = drawing_bbox(lines + points, padding=0.05 * bbox[2])
        self.bbox = bbox
        self.drawing_W = bbox[2]
        self.drawing_H = bbox[3]

        if len(lines) > 0:
            vertex, index, colors = build_buffers(lines, line_colors)

            vbo = self.ctx.buffer(vertex)
            ibo = self.ctx.buffer(index)
            cbo = self.ctx.buffer(colors)
            self.line_vao = self.ctx.vertex_array(self.line_prog, [
                (vbo, "2f", "in_position"),
                (cbo, "4f", "in_color"),
            ],
                                                  index_buffer=ibo)
        else:
            self.line_vao = None

        if len(points) > 0:
            point_vertex, point_color = build_point_buffers(
                points, point_colors)
            vbo = self.ctx.buffer(point_vertex)
            cbo = self.ctx.buffer(point_color)
            self.point_vao = self.ctx.vertex_array(self.point_prog, [
                (vbo, "2f", "in_position"),
                (cbo, "4f", "in_color"),
            ])
        else:
            self.point_vao = None

        # Set the desired properties for the lines.
        # Note:
        # - round cap/ends are used if miter_limit < 0
        # - antialias value is in model space and should probably be scaled to be ~1.5px in
        #   screen space

        self.line_prog["linewidth"].value = lw
        self.line_prog["antialias"].value = 1.5
        self.line_prog["miter_limit"].value = -1
        # self.line_prog["color"].value = 0, 0, 0, 1

        self.update_projection()
Example #6
0
def run(args):
    img = cv2.imread(args.img)
    img = resize_to_px_count(img, 1000**2)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blur_type = 'bilateral'
    # blur_type = 'gauss'
    if blur_type == 'gauss':
        sigma = 8
        if sigma > 0:
            gray = cv2.GaussianBlur(gray, ksize=(0, 0), sigmaX=sigma)
    elif blur_type == 'bilateral':
        sigmaColor = 20
        sigmaSpace = 5
        blurred = cv2.bilateralFilter(img,
                                      d=-1,
                                      sigmaColor=sigmaColor,
                                      sigmaSpace=sigmaSpace)

        # gray = cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY)
        # sigma = 3
        # gray = cv2.GaussianBlur(gray, ksize=(0, 0), sigmaX=sigma)

        # cv2.imshow("cv: gray", gray)
        # while True:
        #     c = cv2.waitKey(0)
        #     if c == ord('q'):
        #         sys.exit(1)

    cmyk = bgr2cmyk(blurred)
    to_draw = {}
    N_hatches = args.N_hatches
    for i, name in enumerate("CMYK"):
        to_draw[name] = multi_hatch(cmyk[:, :, i],
                                    args.hatch_step_px,
                                    contour_tolerance=1,
                                    N_hatches=N_hatches,
                                    dark=False)
        to_draw[name] = [x[:, ::-1] for x in to_draw[name]]  # swap x, y

    if args.rotate:
        to_draw = rotate(to_draw)

    page_conf = load_page_conf(args.format)

    x_margin_mm = args.margins
    y_margin_mm = args.margins
    H = page_conf['H']  # 210 # A4
    W = page_conf['W']  # 297 # A4

    # to_draw = rotate(to_draw)
    to_draw = resize_and_center(to_draw, H, W, x_margin_mm, x_margin_mm,
                                y_margin_mm, y_margin_mm)
    border = rounded_rect(drawing_bbox(to_draw), 15)
    vis_drawing([border], 'b:', linewidth=0.5)
    to_draw = mask_drawing(to_draw, border)
    to_draw = optimize(to_draw,
                       line_simplification_threshold=0.1,
                       path_drop_threshold=2.0,
                       path_join_threshold=1.0)
    vis_drawing(to_draw,
                layer_options={
                    'C': (['c-'], dict(linewidth=0.1, alpha=0.5)),
                    'M': (['m-'], dict(linewidth=0.1, alpha=0.5)),
                    'Y': (['y-'], dict(linewidth=0.1, alpha=0.5)),
                    'K': (['k-'], dict(linewidth=0.1, alpha=0.5)),
                })
    plt.plot([0, W, W, 0, 0], [0, 0, H, H, 0], 'k:')
    plt.show()

    with Plotter('/dev/ttyUSB0', 9600) as p:
        p.load_config(args.opconfig)
        p.set_input_limits((0, 0), (W, 0), (0, H), (W, H))
        p.draw_polylines(to_draw)

    # cv2.imshow("cv: canvas", canvas)
    # while True:
    #     c = cv2.waitKey(0)
    #     if c == ord('q'):
    #         break
    # plt.contour(gray, levels=levels,
    #             colors='k', linewidths=0.1)
    # plt.axis('equal')
    # plt.gca().invert_yaxis()
    # plt.show()
    return 0