Beispiel #1
0
def main():
    with session_scope() as sess:
        shapes = sess.query(models.Shape).all()

    pbar = tqdm(shapes)
    shape: models.Shape
    for shape in pbar:
        pbar.set_description(f"{shape.id!s}")

        new_obj_path = shape.models_dir / 'uvmapped_v2.resized.obj'
        new_mtl_path = shape.models_dir / 'uvmapped_v2.resized.mtl'
        if new_obj_path.exists():
            continue

        mesh = wavefront.read_obj_file(shape.obj_path)
        mesh.resize(1.0)
        with new_obj_path.open('w') as f:
            wavefront.save_obj_file(f, mesh)
        shutil.copy2(shape.mtl_path, new_mtl_path)
Beispiel #2
0
def import_jsd_mesh(jsd_mesh):
    if jsd_mesh['type'] == 'wavefront':
        mesh = wavefront.read_obj_file(jsd_mesh['path'])
    elif jsd_mesh['type'] == 'inline':
        vertices = jsd_mesh['vertices']
        normals = jsd_mesh['normals'] if 'normals' in jsd_mesh else []
        uvs = jsd_mesh['uvs'] if 'uvs' in jsd_mesh else []
        mesh = Mesh(np.array(vertices), np.array(normals), np.array(uvs),
                    jsd_mesh['faces'], jsd_mesh['materials'], [], [])
    else:
        raise RuntimeError("Unknown mesh type {}".format(jsd_mesh['type']))

    if 'size' in jsd_mesh:
        mesh.resize(jsd_mesh['size'])
    elif 'scale' in jsd_mesh:
        mesh.rescale(jsd_mesh['scale'])

    if 'uv_scale' in jsd_mesh:
        uv_scale = float(jsd_mesh['uv_scale'])
        logger.info("UV scale is set to {:.04f} for mesh".format(uv_scale))
        mesh.uv_scale = uv_scale

    return mesh
Beispiel #3
0
 def load(self, size=100) -> object:
     mesh = wavefront.read_obj_file(self.obj_path)
     mesh.resize(size)
     materials = wavefront.read_mtl_file(self.mtl_path, mesh)
     return mesh, materials
Beispiel #4
0
def main():
    logger.info("Loading models.")
    with session_scope() as sess:
        shapes = (
            sess.query(models.Shape).order_by(models.Shape.id.asc())
            # .filter_by(source='hermanmiller')
            .all())

    radmap_path = '/projects/grail/kpar/data/envmaps/rnl_cross.pfm'
    radmap = jsd.import_radiance_map(dict(path=radmap_path))
    scene = Scene()
    scene.set_radiance_map(radmap)

    dist = 200
    camera = PerspectiveCamera(size=(1000, 1000),
                               fov=0,
                               near=0.1,
                               far=5000.0,
                               position=(0, 0, -dist),
                               clear_color=(1, 1, 1, 0),
                               lookat=(0, 0, 0),
                               up=(0, 1, 0))

    renderer = SceneRenderer(scene,
                             camera=camera,
                             gamma=2.2,
                             ssaa=3,
                             tonemap='reinhard',
                             reinhard_thres=3.0,
                             show=args.preview)
    renderer.__enter__()

    for i, shape in enumerate(shapes):
        if shape.data_exists(config.SHAPE_REND_PHONG_NAME):
            continue
        if i < args.start:
            continue
        if args.end != -1 and i >= args.end:
            logger.info("Hit end {}={}.".format(i, args.end))
            return

        logger.info("[%d/%d] Processing %d", i + 1, len(shapes), shape.id)

        print(shape.obj_path)
        if not shape.obj_path.exists():
            logger.error('Shape %d does not have a UV mapped model.', shape.id)
            continue

        mesh = wavefront.read_obj_file(shape.obj_path)
        mesh.resize(100)
        materials = wavefront.read_mtl_file(shape.mtl_path, mesh)
        scene.add_mesh(mesh)

        for mat_name, mat in materials.items():
            roughness = math.sqrt(2 / (mat.specular_exponent + 2))
            # material = BlinnPhongMaterial(mat.diffuse_color,
            #                               mat.specular_color,
            #                               roughness)
            material = BlinnPhongMaterial(diff_color=(0.1, 0.28, 0.8),
                                          spec_color=(0.04, 0.04, 0.04),
                                          roughness=0.1)
            scene.put_material(mat_name, material)

        data_name = f'preview/phong.500x500.png'
        # if shape.data_exists(data_name):
        #     continue

        camera.position = spherical_to_cartesian(dist,
                                                 *shape.get_demo_angles())
        camera.fov = 50
        if args.preview:
            renderer.draw()
            renderer.swap_buffers()
        # Set format to RGBA so we can crop foreground using alpha.
        image = renderer.render_to_image(format='rgba')
        image = np.clip(image, 0, 1)
        fg_bbox = mask_bbox(image[:, :, 3] > 0)
        image = crop_tight_fg(image[:, :, :3], (500, 500),
                              bbox=fg_bbox,
                              use_pil=True)
        vis.image(image.transpose((2, 0, 1)), win='rend-preview')

        shape.save_data(config.SHAPE_REND_PHONG_NAME, image)
        scene.clear()
Beispiel #5
0
def main():
    logger.info("Loading models.")
    with session_scope() as sess:
        shapes = sess.query(models.Shape).order_by(models.Shape.id.desc()).all()

    radmap_path = '/projects/grail/kpar/data/envmaps2/rnl.cross.exr'
    radmap = jsd.import_radiance_map(dict(path=radmap_path))
    scene = Scene()
    scene.set_radiance_map(radmap)

    dist = 200
    camera = PerspectiveCamera(
        size=(200, 200), fov=0, near=0.1, far=5000.0,
        position=(0, 0, -dist), clear_color=(1, 1, 1, 0),
        lookat=(0, 0, 0), up=(0, 1, 0))

    renderer = SceneRenderer(scene, camera=camera,
                             gamma=2.2, ssaa=3,
                             tonemap='reinhard',
                             reinhard_thres=3.0,
                             show=args.preview)
    renderer.__enter__()

    fovs = [50]
    elevations = np.linspace(math.pi/4, math.pi/2 + math.pi/16, 10)
    max_azimuth_samps = 36
    azimuth_by_elev = {}
    n_viewpoints = 0
    for phi in elevations:
        n_azimuths = int(round(max_azimuth_samps * math.sin(phi)))
        azimuth_by_elev[phi] = np.linspace(0, 2*math.pi, n_azimuths)
        n_viewpoints += n_azimuths

    for i, shape in enumerate(shapes):
        last_name = "alignment/renderings/fov=50,theta=6.28318531,phi=1.76714587.png"
        if shape.data_exists(last_name):
            tqdm.write(f'Skipping {shape.id}')
            continue

        if i < args.start:
            continue
        if args.end != -1 and i >= args.end:
            logger.info("Hit end {}={}.".format(i, args.end))
            return

        logger.info("[%d/%d] Processing %d", i + 1, len(shapes), shape.id)

        if not shape.obj_path.exists():
            logger.error('Shape %d does not have a UV mapped model.', shape.id)

        mesh = wavefront.read_obj_file(shape.obj_path)
        mesh.resize(100)
        materials = wavefront.read_mtl_file(shape.mtl_path, mesh)
        scene.add_mesh(mesh)

        for mat_name, mat in materials.items():
            roughness = math.sqrt(2/(mat.specular_exponent + 2))
            scene.put_material(mat_name,
                               BlinnPhongMaterial(mat.diffuse_color,
                                                  mat.specular_color,
                                                  roughness))

        iterables = []
        for fov, phi in itertools.product(fovs, elevations):
            for theta in azimuth_by_elev[phi]:
                iterables.append((fov, theta, phi))

        pbar = tqdm(iterables)
        for fov, theta, phi in pbar:
            rend_fname = f"fov={fov},theta={theta:.08f},phi={phi:.08f}.png"
            data_name = f'alignment/renderings/{rend_fname}'
            if shape.data_exists(data_name):
                continue
            pbar.set_description(rend_fname)

            camera.position = spherical_to_cartesian(dist, theta, phi)
            camera.fov = fov
            if args.preview:
                renderer.draw()
                renderer.swap_buffers()
             # Set format to RGBA so we can crop foreground using alpha.
            image = renderer.render_to_image(format='rgba')
            image = np.clip(image, 0, 1)
            fg_bbox = mask_bbox(image[:, :, 3] > 0)
            image = crop_tight_fg(
                image[:, :, :3], (100, 100), bbox=fg_bbox, use_pil=True)
            vis.image(image.transpose((2, 0, 1)), win='rend-preview')

            shape.save_data(data_name, image)
        scene.clear()