Ejemplo n.º 1
0
    def __init__(self, width=600, height=600, title="Hello", **kwargs):
        self._ctx = bimpy.Context()
        self._ctx.init(width, height, title, **kwargs)

        def mouse_button(button, down, x, y):
            self.on_mouse_button(button, down, x, y)

        self._ctx.mouse_button_callback = mouse_button

        def mouse_pos(x, y):
            self.on_mouse_position(x, y)

        self._ctx.mouse_position_callback = mouse_pos

        def keyboard(key, action, mods):
            if key < 255:
                key = chr(key)
            if action == 1:
                self.keys[key] = 1
            elif action == 0:
                if key in self.keys:
                    del self.keys[key]
            self.on_keyboard(key, action == 1, mods)

        self._ctx.keyboard_callback = keyboard
        self.keys = {}
        self.image = None
Ejemplo n.º 2
0
def run_visual(mods):
    ctx = bimpy.Context()
    ctx.init(1280, 720, "test")
    while not ctx.should_close():
        with ctx:
            for mod in mods:
                mod.visualize()
Ejemplo n.º 3
0
def main():
	global CTX

	ctx = bimpy.Context()
	ctx.init(1200, 1200, "Image")
	with ctx:
		bimpy.themes.set_light_theme()


	socket_thread = threading.Thread(target = thread_socket_func, args = (8883, ))
	socket_thread.start()

	message_thread = threading.Thread(target = message_thread_func)
	message_thread.start()

	previous_n_points = 0
	clear_flag = False
	while not ctx.should_close():
		with ctx:
			bimpy.set_next_window_pos(bimpy.Vec2(120, 120), bimpy.Condition.Once)
			bimpy.set_next_window_size(bimpy.Vec2(400, 400), bimpy.Condition.Once)
			bimpy.begin("Window #1")
			
			bimpy.text("This is text!")
			
			if bimpy.button("Send A Lot Of Messages"):
				temp_messages = [make_message_text("log", "Message #" + str(i)) for i in range(560)]
				send_messages(CTX.message_pipeline, temp_messages)
			
			if bimpy.button("Send A Lot Of Random Points"):
				temp_messages = [make_message_point("point", (random.randrange(400 + i), random.randrange(400 + i))) for i in range(20)]
				send_messages(CTX.message_pipeline, temp_messages)				
			
			if bimpy.button("Clear Flag"):
				clear_flag = not clear_flag
			
			bimpy.text("Text from events:\n%s" % (CTX.data.text))

			bimpy.end()

			draw_window_drawing(ctx, 400, 400, "Sample Drawing", CTX.data.points)

	log("Exited rendering thread")

	log("Sending exit to message_thread")
	send_message_text(CTX.message_pipeline, "exit", "")

	log("Waiting for message_thread")
	message_thread.join()
	CTX.server_socket_running = False
	if CTX.server_socket:
		for c, info in CTX.server_socket.connections:
			c.send(b'exit')

	log("Waiting for socket_thread")
	socket_thread.join()

	log("Bye")
Ejemplo n.º 4
0
    def __init__(self, width, height, title):
        self.width = width
        self.height = height
        self.identify = False

        self.ctx = bimpy.Context()
        self.ctx.init(width, height, title)

        self.min_aspect_ratio = bimpy.Float(0.0)
Ejemplo n.º 5
0
    def init(self):
        # new instance

        ctx = bimpy.Context()

        # init
        ctx.init(conf.width, conf.height, LANG.name)

        # load font and theme
        # set_yellow()
        bimpy.add_font_from_file_ttf(conf.font, conf.font_size)
        bimpy.themes.set_light_theme()

        self.ctx = ctx
Ejemplo n.º 6
0
def main():
    ctx = bimpy.Context()
    ctx.init(1200, 800, 'tester')

    dash_window = DashWindow()
    canvas_window = CanvasWindow()

    while not ctx.should_close():
        with ctx:
            # bimpy.show_demo_window()

            dash_window.render()

            # lines data  [dash lines] -> [canvas lines draw]
            canvas_window.lines_draw_component.set_lines(
                dash_window.lines_componnet.get_line_data())

            # highlight line index  [dash lines] -> [canvas lines draw]
            canvas_window.lines_draw_component.set_highlight_line_index(
                dash_window.lines_componnet.get_highlight_line_index())

            # waitting draw line index  [dash lines] -> [canvas lines draw]
            canvas_window.lines_draw_component.set_waitting_draw_line_index(
                dash_window.lines_componnet.get_waitting_draw_line_index())

            # convex points  [dash convex] -> [canvas convex draw]
            canvas_window.convex_draw_component.set_convex_points(
                dash_window.convex_component.get_convex_data())

            # waitting draw line index  [dash lines] -> [canvas user lines draw]
            canvas_window.user_line_draw_component.set_waitting_draw_line_index(
                dash_window.lines_componnet.get_waitting_draw_line_index())
            
            # convex draw [dash convex] -> [canvas user convex draw]
            canvas_window.user_convex_draw_component.set_convex_draw_flag(
                dash_window.convex_component.get_convex_draw_flag())
            
            canvas_window.render()

            # waitting draw line value  [canvas lines draw] -> [dash lines]
            dash_window.lines_componnet.set_waitting_draw_line_value(
                canvas_window.user_line_draw_component.get_waitting_draw_line_value())

            # convex draw [canvas user convex draw] -> [dash convex]
            dash_window.convex_component.set_convex_draw_value(
                canvas_window.user_convex_draw_component.get_convex_draw_value())
            # logging.render()

    dash_window.close()
    canvas_window.close()
Ejemplo n.º 7
0
def main():
    selected_compiler = bimpy.Int()
    ctx = bimpy.Context()
    ctx.init(WIDTH, HEIGHT, "Virtual enviroment manager")

    environments = getAvailableEnviroments()
    compilers_list = list(data.compilers.keys())

    show_new_env_menu = False

    while (not ctx.should_close()):
        with ctx:
            bimpy.set_next_window_pos(bimpy.Vec2(0, 0), bimpy.Condition.Once)
            bimpy.set_next_window_size(bimpy.Vec2(WIDTH, HEIGHT),
                                       bimpy.Condition.Once)
            bimpy.begin("Enviroments",bimpy.Bool(True), \
                bimpy.WindowFlags.NoCollapse and bimpy.WindowFlags.NoResize)
            bimpy.text(sys.version)
            bimpy.columns(2)
            for enviroment in environments:
                if bimpy.button(enviroment):
                    compiler = list(data.compilers.values())[
                        selected_compiler.
                        value] if selected_compiler.value != 0 else ""
                    subprocess.call(
                        ['start', environments[enviroment], compiler],
                        shell=True)
                bimpy.next_column()
                if bimpy.button("O##" + enviroment):
                    subprocess.Popen(r'explorer /select,' +
                                     os.path.dirname(environments[enviroment]))
                    #os.startfile(os.path.realpath(os.path.dirname(environments[enviroment])))
                bimpy.next_column()
            bimpy.columns(1)
            if bimpy.combo("Compiler", selected_compiler, compilers_list):
                pass

            # if bimpy.button("Add new enviroment"):
            #     new_env_ctx = BimpyContext(WIDTH, HEIGHT, "New enviroment menu")
            #     while(not new_env_ctx.ctx.should_close()):
            #         with new_env_ctx.ctx:
            #             bimpy.begin("dsad")
            #             bimpy.text("d")
            #             bimpy.end()

            # if bimpy.button("Create new enviroment"):

            bimpy.end()
Ejemplo n.º 8
0
def main():
    process_envvars()
    ctx = bimpy.Context()
    ctx.init(600, 800, "Slim's Editor")

    while not ctx.should_close():
        with ctx:
            render_menu_bar()

            for frame in open_frames:
                frame.render()

        process_menu_bar_events()
        for frame in open_frames:
            frame.process_events()

        open_frames_to_close = []
        for i, frame in enumerate(open_frames):
            if not frame.opened.value:
                open_frames_to_close.append(i)

        for i in sorted(open_frames_to_close, reverse=True):
            del open_frames[i]
Ejemplo n.º 9
0
import bimpy as b
from PIL import Image

c = b.Context()
c.init(1200, 1200, "bimpy test")

img = Image.new(
    "RGBA",
    (512, 512),
)
px = img.load()
for x in range(512):
    for y in range(512):
        r = int(255.0 * float(x) / 512.0)
        g = int(255.0 * float(y) / 512.0)
        px[x, y] = (r, g, max(255 - r - g, 0), 255)

b_img = b.Image(img)

b_f1 = b.Float()
b_f2 = b.Float()
b_f3 = b.Float()

while not c.should_close():
    with c:
        b.text("hi")
        if b.button("cat"):
            print("mew")

        b.input_float("float1", b_f1, 0.0, 1.0)
        b.image(b_img)
Ejemplo n.º 10
0
    res = ((current_time) - (g_last_timestamp))
    g_last_timestamp = current_time
    return res


def fail(msg):
    print(((bcolors.FAIL) + ("{:8d} FAIL ".format(milli_since_last())) +
           (msg) + (bcolors.ENDC)))
    sys.stdout.flush()


def plog(msg):
    print(((bcolors.OKGREEN) + ("{:8d} LOG ".format(milli_since_last())) +
           (msg) + (bcolors.ENDC)))
    sys.stdout.flush()


args = docopt.docopt(__doc__, version="0.0.1")
if (args["--verbose"]):
    print(args)
ctx = b.Context()
ctx.init(600, 600, "Hello")
str = b.String()
f = b.Float()
while (not (ctx.should_close())):
    with ctx:
        b.text("hello world")
        if (b.button("OK")):
            print(str.value)
        b.input_text("string", str, 256)
        b.slider_float("float", f, (0.0e+0), (1.e+0))
Ejemplo n.º 11
0
def sample(cfg, logger):
    model = Model(
        startf=cfg.MODEL.START_CHANNEL_COUNT,
        layer_count= cfg.MODEL.LAYER_COUNT,
        maxf=cfg.MODEL.MAX_CHANNEL_COUNT,
        latent_size=cfg.MODEL.LATENT_SPACE_SIZE,
        truncation_psi=cfg.MODEL.TRUNCATIOM_PSI,
        truncation_cutoff=cfg.MODEL.TRUNCATIOM_CUTOFF,
        mapping_layers=cfg.MODEL.MAPPING_LAYERS,
        channels=3)
    model.eval()

    logger.info("Trainable parameters generator:")
    count_parameters(model.generator)

    model_dict = {
        'generator_s': model.generator,
        'mapping_fl_s': model.mapping,
        'dlatent_avg': model.dlatent_avg,
    }

    checkpointer = Checkpointer(cfg,
                                model_dict,
                                logger=logger,
                                save=True)

    checkpointer.load()

    ctx = bimpy.Context()
    remove = bimpy.Bool(False)
    layers = bimpy.Int(8)

    ctx.init(1800, 1600, "Styles")

    rnd = np.random.RandomState(5)
    latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE)
    sample = torch.tensor(latents).float().cuda()

    def update_image(sample):
        with torch.no_grad():
            torch.manual_seed(0)
            model.eval()
            x_rec = model.generate(layers.value, remove.value, z=sample)
            #model.generator.set(l.value, c.value)
            resultsample = ((x_rec * 0.5 + 0.5) * 255).type(torch.long).clamp(0, 255)
            resultsample = resultsample.cpu()[0, :, :, :]

            return resultsample.type(torch.uint8).transpose(0, 2).transpose(0, 1)

    with torch.no_grad():
        save_image(model.generate(8, True, z=sample) * 0.5 + 0.5, 'sample.png')

    im = bimpy.Image(update_image(sample))
    while(not ctx.should_close()):
        with ctx:

            bimpy.set_window_font_scale(2.0)

            if bimpy.checkbox('REMOVE BLOB', remove):
                im = bimpy.Image(update_image(sample))
            if bimpy.button('NEXT'):
                latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE)
                sample = torch.tensor(latents).float().cuda()
                im = bimpy.Image(update_image(sample))
            if bimpy.slider_int("Layers", layers, 0, 8):
                im = bimpy.Image(update_image(sample))
            bimpy.image(im, bimpy.Vec2(1024, 1024))
Ejemplo n.º 12
0
def sample(cfg, logger):
    torch.cuda.set_device(0)
    model = Model(startf=cfg.MODEL.START_CHANNEL_COUNT,
                  layer_count=cfg.MODEL.LAYER_COUNT,
                  maxf=cfg.MODEL.MAX_CHANNEL_COUNT,
                  latent_size=cfg.MODEL.LATENT_SPACE_SIZE,
                  truncation_psi=cfg.MODEL.TRUNCATIOM_PSI,
                  truncation_cutoff=cfg.MODEL.TRUNCATIOM_CUTOFF,
                  mapping_layers=cfg.MODEL.MAPPING_LAYERS,
                  channels=cfg.MODEL.CHANNELS,
                  generator=cfg.MODEL.GENERATOR,
                  encoder=cfg.MODEL.ENCODER)
    model.cuda(0)
    model.eval()
    model.requires_grad_(False)

    decoder = model.decoder
    encoder = model.encoder
    mapping_tl = model.mapping_d
    mapping_fl = model.mapping_f
    dlatent_avg = model.dlatent_avg

    logger.info("Trainable parameters generator:")
    count_parameters(decoder)

    logger.info("Trainable parameters discriminator:")
    count_parameters(encoder)

    arguments = dict()
    arguments["iteration"] = 0

    model_dict = {
        'discriminator_s': encoder,
        'generator_s': decoder,
        'mapping_tl_s': mapping_tl,
        'mapping_fl_s': mapping_fl,
        'dlatent_avg': dlatent_avg
    }

    checkpointer = Checkpointer(cfg, model_dict, {}, logger=logger, save=False)

    extra_checkpoint_data = checkpointer.load()

    model.eval()

    layer_count = cfg.MODEL.LAYER_COUNT

    def encode(x):
        Z, _ = model.encode(x, layer_count - 1, 1)
        Z = Z.repeat(1, model.mapping_f.num_layers, 1)
        return Z

    def decode(x):
        layer_idx = torch.arange(2 * layer_count)[np.newaxis, :, np.newaxis]
        ones = torch.ones(layer_idx.shape, dtype=torch.float32)
        coefs = torch.where(layer_idx < model.truncation_cutoff, ones, ones)
        # x = torch.lerp(model.dlatent_avg.buff.data, x, coefs)
        return model.decoder(x, layer_count - 1, 1, noise=True)

    path = 'dataset_samples/faces/realign1024x1024'

    paths = list(os.listdir(path))
    paths.sort()
    paths_backup = paths[:]
    randomize = bimpy.Bool(True)
    current_file = bimpy.String("")

    ctx = bimpy.Context()

    attribute_values = [bimpy.Float(0) for i in indices]

    W = [
        torch.tensor(np.load("principal_directions/direction_%d.npy" % i),
                     dtype=torch.float32) for i in indices
    ]

    rnd = np.random.RandomState(5)

    def loadNext():
        img = np.asarray(Image.open(path + '/' + paths[0]))
        current_file.value = paths[0]
        paths.pop(0)
        if len(paths) == 0:
            paths.extend(paths_backup)

        if img.shape[2] == 4:
            img = img[:, :, :3]
        im = img.transpose((2, 0, 1))
        x = torch.tensor(np.asarray(im, dtype=np.float32),
                         device='cpu',
                         requires_grad=True).cuda() / 127.5 - 1.
        if x.shape[0] == 4:
            x = x[:3]

        needed_resolution = model.decoder.layer_to_resolution[-1]
        while x.shape[2] > needed_resolution:
            x = F.avg_pool2d(x, 2, 2)
        if x.shape[2] != needed_resolution:
            x = F.adaptive_avg_pool2d(x,
                                      (needed_resolution, needed_resolution))

        img_src = ((x * 0.5 + 0.5) * 255).type(torch.long).clamp(
            0, 255).cpu().type(torch.uint8).transpose(0,
                                                      2).transpose(0,
                                                                   1).numpy()

        latents_original = encode(x[None, ...].cuda())
        latents = latents_original[0, 0].clone()
        latents -= model.dlatent_avg.buff.data[0]

        for v, w in zip(attribute_values, W):
            v.value = (latents * w).sum()

        for v, w in zip(attribute_values, W):
            latents = latents - v.value * w

        return latents, latents_original, img_src

    def loadRandom():
        latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE)
        lat = torch.tensor(latents).float().cuda()
        dlat = mapping_fl(lat)
        layer_idx = torch.arange(2 * layer_count)[np.newaxis, :, np.newaxis]
        ones = torch.ones(layer_idx.shape, dtype=torch.float32)
        coefs = torch.where(layer_idx < model.truncation_cutoff, ones, ones)
        dlat = torch.lerp(model.dlatent_avg.buff.data, dlat, coefs)
        x = decode(dlat)[0]
        img_src = ((x * 0.5 + 0.5) * 255).type(torch.long).clamp(
            0, 255).cpu().type(torch.uint8).transpose(0,
                                                      2).transpose(0,
                                                                   1).numpy()
        latents_original = dlat
        latents = latents_original[0, 0].clone()
        latents -= model.dlatent_avg.buff.data[0]

        for v, w in zip(attribute_values, W):
            v.value = (latents * w).sum()

        for v, w in zip(attribute_values, W):
            latents = latents - v.value * w

        return latents, latents_original, img_src

    latents, latents_original, img_src = loadNext()

    ctx.init(1800, 1600, "Styles")

    def update_image(w, latents_original):
        with torch.no_grad():
            w = w + model.dlatent_avg.buff.data[0]
            w = w[None, None, ...].repeat(1, model.mapping_f.num_layers, 1)

            layer_idx = torch.arange(model.mapping_f.num_layers)[np.newaxis, :,
                                                                 np.newaxis]
            cur_layers = (7 + 1) * 2
            mixing_cutoff = cur_layers
            styles = torch.where(layer_idx < mixing_cutoff, w,
                                 latents_original)

            x_rec = decode(styles)
            resultsample = ((x_rec * 0.5 + 0.5) * 255).type(torch.long).clamp(
                0, 255)
            resultsample = resultsample.cpu()[0, :, :, :]
            return resultsample.type(torch.uint8).transpose(0,
                                                            2).transpose(0, 1)

    im_size = 2**(cfg.MODEL.LAYER_COUNT + 1)
    im = update_image(latents, latents_original)
    print(im.shape)
    im = bimpy.Image(im)

    display_original = True

    seed = 0

    while not ctx.should_close():
        with ctx:
            new_latents = latents + sum(
                [v.value * w for v, w in zip(attribute_values, W)])

            if display_original:
                im = bimpy.Image(img_src)
            else:
                im = bimpy.Image(update_image(new_latents, latents_original))

            bimpy.begin("Principal directions")
            bimpy.columns(2)
            bimpy.set_column_width(0, im_size + 20)
            bimpy.image(im)
            bimpy.next_column()

            for v, label in zip(attribute_values, labels):
                bimpy.slider_float(label, v, -40.0, 40.0)

            bimpy.checkbox("Randomize noise", randomize)

            if randomize.value:
                seed += 1

            torch.manual_seed(seed)

            if bimpy.button('Next'):
                latents, latents_original, img_src = loadNext()
                display_original = True
            if bimpy.button('Display Reconstruction'):
                display_original = False
            if bimpy.button('Generate random'):
                latents, latents_original, img_src = loadRandom()
                display_original = False

            if bimpy.input_text(
                    "Current file", current_file,
                    64) and os.path.exists(path + '/' + current_file.value):
                paths.insert(0, current_file.value)
                latents, latents_original, img_src = loadNext()

            bimpy.end()
Ejemplo n.º 13
0
    ]
    bp.combo("combo", item_current, items)
    bp.same_line()
    help_marker(
        "Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, and demonstration of various flags.\n"
    )

    #  To wire InputText() with std::string or any other custom string type,
    #  see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file.
    bp.input_text("input text", str0, 128)
    bp.same_line()
    help_marker(
        "USER:\nHold SHIFT or use mouse to select text.\n"
        "CTRL+Left/Right to word jump.\n"
        "CTRL+A or double-click to select all.\n"
        "CTRL+X,CTRL+C,CTRL+V clipboard.\n"
        "CTRL+Z,CTRL+Y undo/redo.\n"
        "ESCAPE to revert.\n\nPROGRAMMER:\nYou can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated in imgui_demo.cpp)."
    )

    bp.end()


ctx = bp.Context()

ctx.init(600, 600, "Demo")

while not ctx.should_close():
    with ctx:
        show_demo_window()
Ejemplo n.º 14
0
import bimpy as bp

context = bp.Context()
context.init(600, 600, "Hello, Bimpy!")
label_content = bp.String()
spinner_content = bp.Float()

while not context.should_close():
    with context:
        bp.text("Hello, Bimpy!")

        if bp.button("Ok"):
            print("Hello!")

        bp.input_text("string", label_content, 256)
        bp.slider_float("float", spinner_content, 0.0, 1.0)
Ejemplo n.º 15
0
def main():

    parser = ArgumentParser(description="Preview animations")

    parser.add_argument("--version",
                        action="version",
                        version="%(prog)s " + __version__)
    parser.add_argument("--width",
                        dest="width",
                        type=int,
                        default=DEF_WIDTH,
                        help="frame width (default: %s)" % DEF_WIDTH)
    parser.add_argument("--height",
                        dest="height",
                        type=int,
                        default=DEF_HEIGHT,
                        help="frame height (default: %s)" % DEF_HEIGHT)
    parser.add_argument("--scale",
                        dest="scale",
                        type=int,
                        default=DEF_SCALE,
                        help="scale preview (default: %s)" % DEF_SCALE)
    parser.add_argument("--double-w",
                        dest="dw",
                        action="store_true",
                        help="double width for 2:1")
    parser.add_argument(
        "--mtime",
        dest="mtime",
        type=int,
        default=DEF_MTIME,
        help="seconds between checks for changes (default: %s)" % DEF_MTIME)

    parser.add_argument("image", help="image to convert")

    args = parser.parse_args()

    def load_image(filename):
        @with_retry
        def load():
            return Image.open(filename).convert("RGB")

        try:
            image = load()
        except IOError:
            parser.error("failed to open the image")

        (w, h) = image.size

        if w % args.width or h % args.height:
            parser.error("%s size is not multiple of tile size (%s, %s)" %
                         (filename, args.width, args.height))

        frames = []
        for y in range(0, h, args.height):
            for x in range(0, w, args.width):
                frames.append((x, y, x + args.width, y + args.height))

        return image, frames

    image, frames = load_image(args.image)
    frame_list = list(range(len(frames)))

    def scale_image(scale, frameno):
        scale_w = scale if not args.dw else scale * 2
        current = image.resize((args.width * scale_w, args.height * scale),
                               box=frames[frame_list[frameno]],
                               resample=0)
        return bimpy.Image(current)

    ctx = bimpy.Context()

    ctx.init(320, 420, "Preview animation")
    orig = bimpy.Image(image)
    scale = bimpy.Int(args.scale)
    fps = bimpy.Int(args.scale)
    frame_list_str = bimpy.String(','.join(map(str, frame_list)))
    im = scale_image(scale.value, 0)

    cur_frame = 0
    paused = False
    start_time = time()
    check_mtime = time()
    last_mtime = os.stat(args.image).st_mtime
    while (not ctx.should_close()):

        if time() - check_mtime > args.mtime:
            if os.stat(args.image).st_mtime != last_mtime:
                last_mtime = os.stat(args.image).st_mtime
                image, frames = load_image(args.image)
                cur_frame = 0
                start_time = time()
                if any([f >= len(frames) for f in frame_list]):
                    frame_list = list(range(len(frames)))
                    frame_list_str = bimpy.String(','.join(map(
                        str, frame_list)))

        ctx.new_frame()
        bimpy.set_next_window_pos(bimpy.Vec2(10, 10), bimpy.Condition.Once)
        bimpy.set_next_window_size(bimpy.Vec2(300, 400), bimpy.Condition.Once)
        bimpy.begin("Image: %s" % args.image)

        if not paused:
            if time() - start_time >= 1. / fps.value:
                start_time = time()
                cur_frame += 1
                if cur_frame == len(frame_list):
                    cur_frame = 0
                im = scale_image(scale.value, cur_frame)

        bimpy.image(orig)
        bimpy.image(im)
        bimpy.text("Frame: %02d" % frame_list[cur_frame])

        if bimpy.slider_int("Scale", scale, 1, 20):
            im = scale_image(scale.value, cur_frame)
        if bimpy.slider_int("FPS", fps, 1, 30):
            start_time = time()
            cur_frame = 0
        if bimpy.input_text("Frames", frame_list_str, 64,
                            bimpy.InputTextFlags.EnterReturnsTrue):
            try:
                new_frame_list = [
                    int(i.strip()) for i in frame_list_str.value.split(",")
                ]
                frame_list = new_frame_list
                start_time = time()
                cur_frame = 0
            except Exception as ex:
                print("Error parsing frame list: %s" % ex)

        if bimpy.button("Play" if paused else "Pause"):
            paused = not paused

        bimpy.end()
        ctx.render()
Ejemplo n.º 16
0
import syphonpy
import time

import bimpy

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import numpy

ctx = bimpy.Context()
ctx.init(1152, 768, "One")

server = syphonpy.SyphonServer("Test")

_texture = glGenTextures(1)


def make_tex(val):
    # glPixelStorei(GL_UNPACK_ALIGNMENT,1)

    glBindTexture(GL_TEXTURE_2D, _texture)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                    GL_LINEAR_MIPMAP_LINEAR)

    l1 = []
    l2 = []
    list_ = []
Ejemplo n.º 17
0
def sample(cfg, logger):
    model = Model(startf=cfg.MODEL.START_CHANNEL_COUNT,
                  layer_count=cfg.MODEL.LAYER_COUNT,
                  maxf=cfg.MODEL.MAX_CHANNEL_COUNT,
                  latent_size=cfg.MODEL.LATENT_SPACE_SIZE,
                  truncation_psi=cfg.MODEL.TRUNCATIOM_PSI,
                  truncation_cutoff=cfg.MODEL.TRUNCATIOM_CUTOFF,
                  mapping_layers=cfg.MODEL.MAPPING_LAYERS,
                  channels=3)
    del model.discriminator
    model.eval()

    #torch.cuda.manual_seed_all(110)

    logger.info("Trainable parameters generator:")
    count_parameters(model.generator)

    if False:
        model_dict = {
            'generator': model.generator,
            'mapping': model.mapping,
            'dlatent_avg': model.dlatent_avg,
        }
    else:
        model_dict = {
            'generator_s': model.generator,
            'mapping_s': model.mapping,
            'dlatent_avg': model.dlatent_avg,
        }

    checkpointer = Checkpointer(cfg, model_dict, logger=logger, save=True)

    file_name = 'karras2019stylegan-ffhq'
    # file_name = 'results/model_final'

    checkpointer.load(file_name=file_name + '.pth')
    # checkpointer.save('final_stripped')

    #sample_b = torch.randn(1, cfg.MODEL.LATENT_SPACE_SIZE).view(-1, cfg.MODEL.LATENT_SPACE_SIZE)

    # for i in range(100):
    #     if i % 20 == 0:
    #         sample_a = sample_b
    #         sample_b = torch.randn(1, cfg.MODEL.LATENT_SPACE_SIZE).view(-1, cfg.MODEL.LATENT_SPACE_SIZE)
    #     x = (i % 20) / 20.0
    #     sample = sample_a * (1.0 - x) + sample_b * x
    #     save_sample(model, sample, i)

    print(model.generator.get_statistics(8))
    # print(model.discriminator.get_statistics(8))

    ctx = bimpy.Context()

    ctx.init(1800, 1600, "Styles")

    rnd = np.random.RandomState(5)
    latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE)
    sample = torch.tensor(latents).float().cuda()

    def update_image(sample):
        with torch.no_grad():
            model.eval()
            x_rec = model.generate(model.generator.layer_count - 1,
                                   1,
                                   z=sample)
            resultsample = ((x_rec * 0.5 + 0.5) * 255).type(torch.long).clamp(
                0, 255)
            resultsample = resultsample.cpu()[0, :, :, :]

            return resultsample.type(torch.uint8).transpose(0,
                                                            2).transpose(0, 1)

    im = update_image(sample)
    print(im.shape)
    im = bimpy.Image(im)

    while (not ctx.should_close()):
        with ctx:
            im = bimpy.Image(update_image(sample))
            bimpy.image(im)
            # if bimpy.button('Ok'):
            if bimpy.button('NEXT'):
                latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE)
                sample = torch.tensor(latents).float().cuda()
                # im = bimpy.Image(update_image(sample))
            #bimpy.set_window_font_scale(2.0)

    exit()

    rnd = np.random.RandomState(111011)
    latents = rnd.randn(1, cfg.MODEL.LATENT_SPACE_SIZE)
    sample = torch.tensor(latents).float().cuda(
    )  # torch.randn(16, cfg.MODEL.LATENT_SPACE_SIZE).view(-1, cfg.MODEL.LATENT_SPACE_SIZE)
    save_sample(model, sample, 0)

    im_count = 16
    canvas = np.zeros([3, im_size * (im_count + 2), im_size * (im_count + 2)])
    cut_layer_b = 0
    cut_layer_e = 2

    styles = model.mapping(sample)
    styles = list(styles.split(1, 1))

    for i in range(im_count):
        torch.cuda.manual_seed_all(110)
        style = [x[i] for x in styles]
        style = torch.cat(style, dim=0)[None, ...]
        rec = model.generator.decode(style, cfg.MODEL.LAYER_COUNT - 1, 0.7)
        place(canvas, rec[0], 1, 2 + i)

        place(canvas, rec[0], 2 + i, 1)

    for i in range(im_count):
        for j in range(im_count):
            style_a = [x[i] for x in styles[:cut_layer_b]]
            style_b = [x[j] for x in styles[cut_layer_b:cut_layer_e]]
            style_c = [x[i] for x in styles[cut_layer_e:]]
            style = style_a + style_b + style_c
            torch.cuda.manual_seed_all(110)
            style = torch.cat(style, dim=0)[None, ...]
            rec = model.generator.decode(style, cfg.MODEL.LAYER_COUNT - 1, 0.7)
            place(canvas, rec[0], 2 + i, 2 + j)

    save_image(torch.Tensor(canvas), 'reconstruction.png')
Ejemplo n.º 18
0
 def __init__(self, width, height, name):
     self.ctx = bimpy.Context()
     self.ctx.init(width, height, name)