def run(args):
    saver = ReproSaver()
    saver.seed()
    R = 150
    phi = 1.6180339
    smaller = R / phi  # golden ratio
    pts = []
    pts.extend(circle_connections(1200, R, np.pi, -np.pi))
    rays = draw_rays(0, 7 * R * phi, 0, np.pi, 30)
    rays.extend(draw_rays(2.5 * R, 7 * R * phi,
                          np.pi / 60,
                          np.pi - np.pi / 60,
                          29))
    rays = shift(rays, np.array([1.7 * R, 0]))
    rays = mask_drawing(rays, circle((0, 0), 1.05 * R, N=50), invert=True)
    pts.extend(rays)
    # pts = mask_drawing(pts, circle((0, 0), R, N=50))
    # pts.extend(circle_connections(230, R, np.pi * 0.3, 0))
    # pts.extend(circle_connections(530, R, np.pi * 0.5, 0))
    # pts.extend(circle_connections(650, R, np.pi * 0.65, np.pi * 0.50))
    # pts.extend(circle_connections(700, R, np.pi * 0.95, np.pi * 0.72))
    # for i in range(1, 18):
    #     smooth_circle = circle_connections(360, R * 1.02**i, np.pi / 180, np.pi / 180)
    #     pts.extend(drop_parts(smooth_circle, space=1, passes=4))
    lines = to_vpype(pts)
    lines.crop(-2.3 * R - smaller, 2.3 * R + smaller, R + smaller, -R - smaller)  # left, bottom, right, top
    pts = from_vpype_lines(lines)
    if not args.nosave:
        saver.add_svg(pts)
    document = vpype.Document(lines)
    # document.extend_page_size(None)
    with open('/tmp/signal_planet.svg', 'w') as fout:
        vpype.write_svg(fout, document)
    vpype_viewer.show(document)
    return 0
Esempio n. 2
0
def run(args):
    saver = ReproSaver('star_results')
    saver.seed()

    if args.rnd:
        description = random_star()
        print(f"description: {description}")
        paths = construct_star(description)
    else:
        N_star = 12
        R = 600
        paths = []
        start_fractions = np.linspace(0.4, 1, 25)
        end_fractions = reversed(start_fractions)
        for start_fraction, end_fraction in zip(start_fractions,
                                                end_fractions):
            start_r = R * start_fraction
            end_r = R * end_fraction
            paths.extend(star_line(N_star, start_r, end_r, 1))

        # vlastovka
        start_fractions = np.geomspace(0.4, 0.65, 20)
        end_fractions = reversed(np.geomspace(0.3, 0.9, 20))
        for start_fraction, end_fraction in zip(start_fractions,
                                                end_fractions):
            start_r = R * start_fraction
            end_r = R * end_fraction
            paths.extend(star_line(N_star, start_r, end_r, 1))

        # stred
        start_fractions = rev_geomspace(0.1, 1, 30)
        end_fractions = start_fractions
        # end_fractions = np.linspace(0.1, 1, 30)
        for start_fraction, end_fraction in zip(start_fractions,
                                                end_fractions):
            start_r = R * start_fraction
            end_r = R * end_fraction
            paths.extend(star_line(N_star, start_r, end_r, 5, mirror=False))

        # stred 2
        start_fractions = rev_geomspace(0.13, 0.7, 20)
        end_fractions = start_fractions
        # end_fractions = np.linspace(0.1, 1, 30)
        for start_fraction, end_fraction in zip(start_fractions,
                                                end_fractions):
            start_r = R * start_fraction
            end_r = R * end_fraction
            paths.extend(star_line(N_star, start_r, end_r, 5, mirror=False))

        paths.extend(star_line(N_star, R, R, 6, mirror=False))

    lines = to_vpype(paths)
    if not args.nosave:
        saver.add_svg(paths)
    document = vpype.Document(lines)
    with open('/tmp/stars.svg', 'w') as fout:
        vpype.write_svg(fout, document)
    if not args.novis:
        vpype_viewer.show(document)
    return 0
Esempio n. 3
0
def run(args):
    saver = ReproSaver()
    saver.seed()
    points = np.random.rand(1000, 2) * 800

    def dist_fn(vp, db):
        return np.sqrt(np.sum(np.square(db - vp.reshape(1, 2)), axis=1))

    vp_tree = VPTree(points, dist_fn)
    # plt.scatter(points[:, 0], points[:, 1])
    paths = vp_tree.plot(color='k', lw=0.5)
    if not args.nosave:
        saver.add_svg(paths)
    vis_drawing(paths, 'k')
    plt.axis('equal')
    plt.show()
    return 0
Esempio n. 4
0
def run(args):
    saver = ReproSaver()
    saver.seed()
    if args.cfg is not None:
        saver.load_seeds(args.cfg)

    H, W = 210, 148
    angle_range = 3

    horizontal_lines = []
    for i in range(1000):
        horizontal_lines.append(
            random_line(H,
                        W,
                        min_angle=np.radians(0 - angle_range / 2),
                        max_angle=np.radians(0 + angle_range / 2)))

    vertical_lines = []
    for i in range(1000):
        vertical_lines.append(
            random_line(H,
                        W,
                        min_angle=np.radians(90 - angle_range / 2),
                        max_angle=np.radians(90 + angle_range / 2)))

    cross = draw_cross(H, W)
    horizontal, vertical = draw_cross_parts(H, W)
    margin = 10
    (horizontal, vertical,
     cross) = resize_and_center([horizontal, vertical, cross], H, W, margin,
                                margin, margin, margin)
    horizontal_lines = mask_drawing(horizontal_lines, horizontal)
    vertical_lines = mask_drawing(vertical_lines, vertical)

    horizontal_lines = jitter_length(horizontal_lines, 0, 5)
    vertical_lines = jitter_length(vertical_lines, 0, 5)

    vertical_lines = mask_drawing(vertical_lines, horizontal, invert=True)

    cross_lines = horizontal_lines
    cross_lines.extend(vertical_lines)
    cross_lines.extend(vertical_lines)
    # cross_lines.append(cross)

    bg_lines = []
    for i in range(300):
        bg_lines.append(random_line(0.2 * H, W))

    bg_lines = shift(bg_lines, (0, 0.8 * H))

    bg_lines = mask_drawing(bg_lines, cross, invert=True)

    pts = []
    pts.extend(cross_lines)
    pts = resize_and_center(pts, H, W, margin, margin, margin, margin)
    # pts.extend(bg_lines)

    lines = to_vpype(pts)
    document = vpype.Document(lines)
    vpype_viewer.show(document)

    if not args.nosave:
        saver.add_svg(pts)
    return 0
Esempio n. 5
0
def run(args):
    saver = ReproSaver()
    saver.seed()
    # H, W = 2100, 2970
    # d_sep = 4
    H, W = 600, 800
    # d_sep = 16
    d_sep = args.sep
    seedpoints_per_path = 40
    mult = args.mult

    if args.img is not None:
        img = cv2.imread(args.img)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = resize_to_max(gray, 800)
        H, W = gray.shape
    else:
        gray = None

    logging.info('Generating noise field')
    field = gen_flow_field(H, W, x_mult=mult)

    # def d_sep_fn(pos):
    #     return d_sep

    def d_sep_fn(pos):
        x, y = clip_to_img(np.round(pos), gray).astype(np.int32)
        val = gray[y, x] / 255
        val = val**2
        return remap(val, 0, 1, 0.8, 10)

    logging.debug('Drawing uniform density streamlines')
    paths = draw_field_uniform(field,
                               d_sep_fn,
                               seedpoints_per_path=seedpoints_per_path,
                               guide=gray)

    gui = Drawer()
    gui.add_lines(paths, 'k')
    gui.draw()
    # vis_field(field)
    for path in paths:
        plt.plot([x for x, _ in path], [y for _, y in path], 'k-', lw=0.3)
    # field_2 = np.zeros_like(field)
    # field_2[:, :, 0] = field[:, :, 1]
    # field_2[:, :, 1] = -field[:, :, 0]
    # paths = draw_field_uniform(field_2, d_sep)
    # # vis_field(field)
    # for path in paths:
    #     plt.plot([x for x, _ in path],
    #              [y for _, y in path], 'b-', lw=0.3)

    export_svg(paths, '/tmp/uniform_flow.svg')
    # plt.axis('image')
    # plt.gca().invert_yaxis()
    # plt.show()

    if not args.nosave:
        saver.add_svg(paths)

    return 0
Esempio n. 6
0
def run(args):
    saver = ReproSaver()
    saver.seed()

    if args.img is not None:
        drawing_name = os.path.splitext(os.path.basename(args.img))[0]
        img = cv2.imread(args.img)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else:
        drawing_name = 'tonal_map'
        orig_tonal_map = np.linspace(0, 1, num=256)
        gray = np.tile(255 * orig_tonal_map.reshape(1, orig_tonal_map.size),
                       (40, 1)).astype(np.uint8)
    gray = resize_to_max(gray, 4000)

    logger.info("drawing_name: {}".format(drawing_name))
    edges = cv2.Canny(gray, 60, 80)
    edge_distance = distance_transform_edt(255 - edges)
    # cv2.imshow("cv: edges", edges)
    # cv2.imshow("cv: edge_distance", edge_distance / np.amax(edge_distance))
    # while True:
    #     c = cv2.waitKey(0)
    #     if c == ord('q'):
    #         import sys
    #         sys.exit(1)

    density = 1 - (gray.astype(np.float64) / 255)

    def stippling_density(density):
        return density**3

    logger.info("stippling")
    with tmp_np_seed(42):
        stippling_fn = CachedComputation(
            os.path.join("cache", f"curly_tsp_stipple_{drawing_name}.pkl"),
            force=args.force)(ascencio2010stippling)
        points = stippling_fn(stippling_density(density),
                              K=200,
                              min_r=2,
                              max_r=75)

    gui = Drawer(point_r=10)
    # gui.add_lines([points.copy()], 'g')
    gui.add_points([points.copy()], 'k')
    # gui.draw()

    logger.info("TSP-ing")
    tsp_fn = CachedComputation(os.path.join("cache",
                                            f"curly_tsp_{drawing_name}.pkl"),
                               force=args.force)(concorde_tsp)
    tsp_pts = tsp_fn(points)

    if args.straight_test:
        logger.debug('Using straight line instead of TSP path')
        tsp_pts = np.array([[20, gray.shape[0] / 2],
                            [gray.shape[1] - 20, gray.shape[0] / 2]])

    gui = Drawer()
    gui.add_lines([tsp_pts], 'k')
    # gui.draw()

    logger.info("squiggling")
    squiggle_fn = CachedComputation(os.path.join(
        "cache", f"curly_tsp_squiggle_{drawing_name}.pkl"),
                                    force=args.force)(chiu2015tone_scribble)

    squiggle_fn = chiu2015tone_scribble

    if os.path.exists(
            'curly_tsp_LUT.npy'
    ) and not args.tonal_map and not args.straight_test and not args.nolut:
        LUT = np.load('curly_tsp_LUT.npy')
        logger.info('using tonal mapping LUT')
        gray = apply_LUT(gray, LUT)

    speed_img = gray
    speed_img = speed_img.astype(np.float32) / 255
    if args.tonal_map or args.straight_test:
        edge_distance = None
    to_draw = [
        squiggle_fn(tsp_pts,
                    r=185,
                    speed_img=speed_img,
                    edge_dist_img=edge_distance)
    ]

    gui = Drawer(lw=5)
    gui.add_lines(to_draw, (0, 0, 0, 1))
    gui.draw()

    if args.tonal_map:
        rendered = render_lines(gray, to_draw[0])
        sigma = 19
        blurred_rendered = cv2.GaussianBlur(rendered,
                                            ksize=(0, 0),
                                            sigmaX=sigma)
        rendered_tonal_map = np.mean(blurred_rendered.astype(np.float32) / 255,
                                     axis=0)
        orig_tonal_map = gray[0, :].astype(np.float32) / 255
        rendered_tones = np.tile(rendered_tonal_map[np.newaxis, :],
                                 (gray.shape[0], 1))
        cv2.imshow("cv: rendered", rendered)
        cv2.imshow("cv: blurred rendered", blurred_rendered)
        cv2.imshow("cv: rendered_tones", rendered_tones)
        cv2.imshow("cv: gray", gray)
        while True:
            c = cv2.waitKey(0)
            if c == ord('q'):
                break
        cv2.destroyAllWindows()
        lut = compute_tonal_mapping(rendered_tonal_map, orig_tonal_map)
        np.save('curly_tsp_LUT', lut)

    if not args.nosave:
        saver.add_svg(to_draw)

    x_margin_mm = 5
    y_margin_mm = 5
    H = 210  # A4
    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 = [np.array([[0, 0], [W, 0], [W, H], [0, H], [0, 0]])]
    # gui = Drawer(point_r=2)
    # gui.add_lines(to_draw, 'b')
    # gui.add_lines(border, 'r')
    # gui.add_points(border, 'g')
    # gui.draw()
    # vis_drawing(to_draw, "r-", linewidth=0.5)
    if not args.noopt:
        to_draw = optimize(to_draw, line_simplification_threshold=0.1)

    vis_drawing(to_draw, "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() as p:
        p.load_config("config.json")
        p.set_input_limits((0, 0), (W, 0), (0, H), (W, H))
        p.draw_polylines(to_draw)

    return 0
Esempio n. 7
0
def run(args):
    img = cv2.imread(args.img)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    scale = 0.3
    gray = cv2.resize(gray, dsize=(0, 0), fx=scale, fy=scale)
    H, W = gray.shape

    to_cover = np.float32(gray) / 255
    to_cover = 1 - to_cover

    sensing_window_sz = 9
    sensing_kernel_sz = 3
    thickness = 3
    subtract = args.sub
    step_size = 2
    all_lines = []
    N_lines = args.N_lines
    max_walk = 400
    walk_stop_ratio = args.wsr
    for line_i in tqdm.tqdm(range(N_lines)):
        ind = np.unravel_index(np.argmax(to_cover, axis=None), to_cover.shape)
        pos_xy = np.array((ind[1], ind[0])).astype(np.float64)
        vel_xy = np.array((0, 0))

        line = [pos_xy.copy()]
        to_cover[int(pos_xy[1]), int(pos_xy[0])] -= subtract
        last_best_val = -float('inf')
        for step_i in range(max_walk):
            if args.sense == 'connected':
                dir_xy, best_val = sense_connected(to_cover, pos_xy + vel_xy)
            else:
                dir_xy, best_val = sense_pool(to_cover,
                                              pos_xy + vel_xy,
                                              window_sz=sensing_window_sz,
                                              kernel_sz=sensing_kernel_sz)
            if best_val <= 0:
                break
            if best_val < last_best_val * walk_stop_ratio:
                break
            last_best_val = best_val

            vel_xy = vel_xy + dir_xy
            old_xy = pos_xy.copy()
            pos_xy += vel_xy
            if args.sub_mode == 'line':
                subtraction_canvas = np.zeros_like(to_cover)
                cv2.line(subtraction_canvas,
                         (int(np.round(old_xy[0])), int(np.round(old_xy[1]))),
                         (int(np.round(pos_xy[0])), int(np.round(pos_xy[1]))),
                         subtract, thickness)
                to_cover -= subtraction_canvas
                line.append(pos_xy.copy())
                lookup_xy = np.round(pos_xy).astype(np.int32)
                if in_bounds(lookup_xy, to_cover):
                    pass
                else:
                    break
            else:
                lookup_xy = np.round(pos_xy).astype(np.int32)
                if in_bounds(lookup_xy, to_cover):
                    to_cover[lookup_xy[1], lookup_xy[0]] -= subtract
                    line.append(pos_xy.copy())
                else:
                    break

        line = np.array(line)
        all_lines.append(line)
        plt.plot(line[:, 0], line[:, 1], 'k-', lw=0.1)
    plt.tight_layout()
    plt.gca().set_aspect('equal', 'box')
    plt.gca().invert_yaxis()
    # from datetime import datetime
    # time_string = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    # plt.savefig(f'results/{time_string}.png', bbox_inches='tight', pad_inches=0,
    #             dpi=600)
    from repro import ReproSaver
    saver = ReproSaver()
    saver.seed_numpy()
    if not args.nosave:
        saver.add_plt_image()
    plt.figure()
    plt.imshow(to_cover)
    plt.show()
    return 0