Spaces:
Runtime error
Runtime error
Commit ·
b7b00e2
1
Parent(s): cd41f5f
Add multiimage and gaussian
Browse filesFiles changed (25)
- app.py+171-38
- assets/example_multi_image/character_1.pngAdded
- assets/example_multi_image/character_2.pngAdded
- assets/example_multi_image/character_3.pngAdded
- assets/example_multi_image/mushroom_1.pngAdded
- assets/example_multi_image/mushroom_2.pngAdded
- assets/example_multi_image/mushroom_3.pngAdded
- assets/example_multi_image/orangeguy_1.pngAdded
- assets/example_multi_image/orangeguy_2.pngAdded
- assets/example_multi_image/orangeguy_3.pngAdded
- assets/example_multi_image/popmart_1.pngAdded
- assets/example_multi_image/popmart_2.pngAdded
- assets/example_multi_image/popmart_3.pngAdded
- assets/example_multi_image/rabbit_1.pngAdded
- assets/example_multi_image/rabbit_2.pngAdded
- assets/example_multi_image/rabbit_3.pngAdded
- assets/example_multi_image/tiger_1.pngAdded
- assets/example_multi_image/tiger_2.pngAdded
- assets/example_multi_image/tiger_3.pngAdded
- assets/example_multi_image/yoimiya_1.pngAdded
- assets/example_multi_image/yoimiya_2.pngAdded
- assets/example_multi_image/yoimiya_3.pngAdded
- trellis/pipelines/trellis_image_to_3d.py+93
- trellis/representations/gaussian/gaussian_model.py+18-3
- trellis/utils/postprocessing_utils.py+130-1
8 unmodified lines91011121314158 unmodified lines24252627282930313233343536373839401 unmodified line42434445464748495051525354557 unmodified lines6364656667686917 unmodified lines878889909192936 unmodified lines1001011021031041051061071081091101 unmodified line11211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315412 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891906 unmodified lines1971981992002012021 unmodified line2042052062072082092102112122132142152162172182192205 unmodified lines2262272282292302312322332342352362372382392402411 unmodified line2432442452462472482492502512522532542552562572584 unmodified lines2632642652662672688 unmodified linesimport torchimport numpy as npimport imageioimport uuidfrom easydict import EasyDict as edictfrom PIL import Imagefrom trellis.pipelines import TrellisImageTo3DPipeline8 unmodified linesdef start_session(req: gr.Request):user_dir = os.path.join(TMP_DIR, str(req.session_hash))print(f'Creating user directory: {user_dir}')os.makedirs(user_dir, exist_ok=True)def end_session(req: gr.Request):user_dir = os.path.join(TMP_DIR, str(req.session_hash))print(f'Removing user directory: {user_dir}')shutil.rmtree(user_dir)def preprocess_image(image: Image.Image) -> Tuple[str, Image.Image]:"""Preprocess the input image.1 unmodified lineimage (Image.Image): The input image.Returns:str: uuid of the trial.Image.Image: The preprocessed image."""processed_image = pipeline.preprocess_image(image)return processed_imagedef pack_state(gs: Gaussian, mesh: MeshExtractResult, trial_id: str) -> dict:return {'gaussian': {**gs.init_params,7 unmodified lines'vertices': mesh.vertices.cpu().numpy(),'faces': mesh.faces.cpu().numpy(),},'trial_id': trial_id,}17 unmodified linesfaces=torch.tensor(state['mesh']['faces'], device='cuda'),)return gs, mesh, state['trial_id']def get_seed(randomize_seed: bool, seed: int) -> int:6 unmodified lines@spaces.GPUdef image_to_3d(image: Image.Image,seed: int,ss_guidance_strength: float,ss_sampling_steps: int,slat_guidance_strength: float,slat_sampling_steps: int,req: gr.Request,) -> Tuple[dict, str]:"""1 unmodified lineArgs:image (Image.Image): The input image.seed (int): The random seed.ss_guidance_strength (float): The guidance strength for sparse structure generation.ss_sampling_steps (int): The number of sampling steps for sparse structure generation.slat_guidance_strength (float): The guidance strength for structured latent generation.slat_sampling_steps (int): The number of sampling steps for structured latent generation.Returns:dict: The information of the generated 3D model.str: The path to the video of the 3D model."""user_dir = os.path.join(TMP_DIR, str(req.session_hash))outputs = pipeline.run(image,seed=seed,formats=["gaussian", "mesh"],preprocess_image=False,sparse_structure_sampler_params={"steps": ss_sampling_steps,"cfg_strength": ss_guidance_strength,},slat_sampler_params={"steps": slat_sampling_steps,"cfg_strength": slat_guidance_strength,},)video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]trial_id = uuid.uuid4()video_path = os.path.join(user_dir, f"{trial_id}.mp4")imageio.mimsave(video_path, video, fps=15)state = pack_state(outputs['gaussian'][0], outputs['mesh'][0], trial_id)torch.cuda.empty_cache()return state, video_path@spaces.GPUdef extract_glb(state: dict,mesh_simplify: float,12 unmodified linesstr: The path to the extracted GLB file."""user_dir = os.path.join(TMP_DIR, str(req.session_hash))gs, mesh, trial_id = unpack_state(state)glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)glb_path = os.path.join(user_dir, f"{trial_id}.glb")glb.export(glb_path)torch.cuda.empty_cache()return glb_path, glb_pathwith gr.Blocks(delete_cache=(600, 600)) as demo:gr.Markdown("""## Image to 3D Asset with [TRELLIS](https://trellis3d.github.io/)* Upload an image and click "Generate" to create a 3D asset. If the image has alpha channel, it be used as the mask. Otherwise, we use `rembg` to remove the background.* If you find the generated 3D asset satisfactory, click "Extract GLB" to extract the GLB file and download it.""")with gr.Row():with gr.Column():image_prompt = gr.Image(label="Image Prompt", format="png", image_mode="RGBA", type="pil", height=300)with gr.Accordion(label="Generation Settings", open=False):seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1)6 unmodified lineswith gr.Row():slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)generate_btn = gr.Button("Generate")1 unmodified linemesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)extract_glb_btn = gr.Button("Extract GLB", interactive=False)with gr.Column():video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True, height=300)model_output = LitModel3D(label="Extracted GLB", exposure=20.0, height=300)download_glb = gr.DownloadButton(label="Download GLB", interactive=False)output_buf = gr.State()# Example images at the bottom of the pagewith gr.Row():examples = gr.Examples(examples=[f'assets/example_image/{image}'5 unmodified linesrun_on_click=True,examples_per_page=64,)# Handlersdemo.load(start_session)demo.unload(end_session)image_prompt.upload(preprocess_image,inputs=[image_prompt],outputs=[image_prompt],)generate_btn.click(get_seed,1 unmodified lineoutputs=[seed],).then(image_to_3d,inputs=[image_prompt, seed, ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps],outputs=[output_buf, video_output],).then(lambda: gr.Button(interactive=True),outputs=[extract_glb_btn],)video_output.clear(lambda: gr.Button(interactive=False),outputs=[extract_glb_btn],)extract_glb_btn.click(4 unmodified lineslambda: gr.Button(interactive=True),outputs=[download_glb],)model_output.clear(lambda: gr.Button(interactive=False),8 unmodified lines910111213148 unmodified lines2324252627282930313233343536371 unmodified line394041424344454647484950515253545556575859606162636465667 unmodified lines74757677787917 unmodified lines9798991001011021036 unmodified lines1101111121131141151161171181191201211221231 unmodified line12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518612 unmodified lines1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802816 unmodified lines2882892902912922932941 unmodified line2962972982993003013023033043053063073083093103113123133143153163173183193203215 unmodified lines3273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643651 unmodified line3673683693703713723733743753763773783793803813824 unmodified lines3873883893903913923933943953963973983994004018 unmodified linesimport torchimport numpy as npimport imageiofrom easydict import EasyDict as edictfrom PIL import Imagefrom trellis.pipelines import TrellisImageTo3DPipeline8 unmodified linesdef start_session(req: gr.Request):user_dir = os.path.join(TMP_DIR, str(req.session_hash))os.makedirs(user_dir, exist_ok=True)def end_session(req: gr.Request):user_dir = os.path.join(TMP_DIR, str(req.session_hash))shutil.rmtree(user_dir)def preprocess_image(image: Image.Image) -> Image.Image:"""Preprocess the input image.1 unmodified lineimage (Image.Image): The input image.Returns:Image.Image: The preprocessed image."""processed_image = pipeline.preprocess_image(image)return processed_imagedef preprocess_images(images: List[Tuple[Image.Image, str]]) -> List[Image.Image]:"""Preprocess a list of input images.Args:images (List[Tuple[Image.Image, str]]): The input images.Returns:List[Image.Image]: The preprocessed images."""images = [image[0] for image in images]processed_images = [pipeline.preprocess_image(image) for image in images]return processed_imagesdef pack_state(gs: Gaussian, mesh: MeshExtractResult) -> dict:return {'gaussian': {**gs.init_params,7 unmodified lines'vertices': mesh.vertices.cpu().numpy(),'faces': mesh.faces.cpu().numpy(),},}17 unmodified linesfaces=torch.tensor(state['mesh']['faces'], device='cuda'),)return gs, meshdef get_seed(randomize_seed: bool, seed: int) -> int:6 unmodified lines@spaces.GPUdef image_to_3d(image: Image.Image,multiimages: List[Tuple[Image.Image, str]],is_multiimage: bool,seed: int,ss_guidance_strength: float,ss_sampling_steps: int,slat_guidance_strength: float,slat_sampling_steps: int,multiimage_algo: Literal["multidiffusion", "stochastic"],req: gr.Request,) -> Tuple[dict, str]:"""1 unmodified lineArgs:image (Image.Image): The input image.multiimages (List[Tuple[Image.Image, str]]): The input images in multi-image mode.is_multiimage (bool): Whether is in multi-image mode.seed (int): The random seed.ss_guidance_strength (float): The guidance strength for sparse structure generation.ss_sampling_steps (int): The number of sampling steps for sparse structure generation.slat_guidance_strength (float): The guidance strength for structured latent generation.slat_sampling_steps (int): The number of sampling steps for structured latent generation.multiimage_algo (Literal["multidiffusion", "stochastic"]): The algorithm for multi-image generation.Returns:dict: The information of the generated 3D model.str: The path to the video of the 3D model."""user_dir = os.path.join(TMP_DIR, str(req.session_hash))if not is_multiimage:outputs = pipeline.run(image,seed=seed,formats=["gaussian", "mesh"],preprocess_image=False,sparse_structure_sampler_params={"steps": ss_sampling_steps,"cfg_strength": ss_guidance_strength,},slat_sampler_params={"steps": slat_sampling_steps,"cfg_strength": slat_guidance_strength,},)else:outputs = pipeline.run_multi_image([image[0] for image in multiimages],seed=seed,formats=["gaussian", "mesh"],preprocess_image=False,sparse_structure_sampler_params={"steps": ss_sampling_steps,"cfg_strength": ss_guidance_strength,},slat_sampler_params={"steps": slat_sampling_steps,"cfg_strength": slat_guidance_strength,},mode=multiimage_algo,)video = render_utils.render_video(outputs['gaussian'][0], num_frames=120)['color']video_geo = render_utils.render_video(outputs['mesh'][0], num_frames=120)['normal']video = [np.concatenate([video[i], video_geo[i]], axis=1) for i in range(len(video))]video_path = os.path.join(user_dir, 'sample.mp4')imageio.mimsave(video_path, video, fps=15)state = pack_state(outputs['gaussian'][0], outputs['mesh'][0])torch.cuda.empty_cache()return state, video_path@spaces.GPU(duration=90)def extract_glb(state: dict,mesh_simplify: float,12 unmodified linesstr: The path to the extracted GLB file."""user_dir = os.path.join(TMP_DIR, str(req.session_hash))gs, mesh = unpack_state(state)glb = postprocessing_utils.to_glb(gs, mesh, simplify=mesh_simplify, texture_size=texture_size, verbose=False)glb_path = os.path.join(user_dir, 'sample.glb')glb.export(glb_path)torch.cuda.empty_cache()return glb_path, glb_path@spaces.GPUdef extract_gaussian(state: dict, req: gr.Request) -> Tuple[str, str]:"""Extract a Gaussian file from the 3D model.Args:state (dict): The state of the generated 3D model.Returns:str: The path to the extracted Gaussian file."""user_dir = os.path.join(TMP_DIR, str(req.session_hash))gs, _ = unpack_state(state)gaussian_path = os.path.join(user_dir, 'sample.ply')gs.save_ply(gaussian_path)torch.cuda.empty_cache()return gaussian_path, gaussian_pathdef prepare_multi_example() -> List[Image.Image]:multi_case = list(set([i.split('_')[0] for i in os.listdir("assets/example_multi_image")]))images = []for case in multi_case:_images = []for i in range(1, 4):img = Image.open(f'assets/example_multi_image/{case}_{i}.png')W, H = img.sizeimg = img.resize((int(W / H * 512), 512))_images.append(np.array(img))images.append(Image.fromarray(np.concatenate(_images, axis=1)))return imagesdef split_image(image: Image.Image) -> List[Image.Image]:"""Split an image into multiple views."""image = np.array(image)alpha = image[..., 3]alpha = np.any(alpha>0, axis=0)start_pos = np.where(~alpha[:-1] & alpha[1:])[0].tolist()end_pos = np.where(alpha[:-1] & ~alpha[1:])[0].tolist()images = []for s, e in zip(start_pos, end_pos):images.append(Image.fromarray(image[:, s:e+1]))return [preprocess_image(image) for image in images]with gr.Blocks(delete_cache=(600, 600)) as demo:gr.Markdown("""## Image to 3D Asset with [TRELLIS](https://trellis3d.github.io/)* Upload an image and click "Generate" to create a 3D asset. If the image has alpha channel, it be used as the mask. Otherwise, we use `rembg` to remove the background.* If you find the generated 3D asset satisfactory, click "Extract GLB" to extract the GLB file and download it.✨New: 1) Experimental multi-image support. 2) Gaussian file extraction.""")with gr.Row():with gr.Column():with gr.Tabs() as input_tabs:with gr.Tab(label="Single Image", id=0) as single_image_input_tab:image_prompt = gr.Image(label="Image Prompt", format="png", image_mode="RGBA", type="pil", height=300)with gr.Tab(label="Multiple Images", id=1) as multiimage_input_tab:multiimage_prompt = gr.Gallery(label="Image Prompt", format="png", type="pil", height=300, columns=3)gr.Markdown("""Input different views of the object in separate images.*NOTE: this is an experimental algorithm without training a specialized model. It may not produce the best results for all images, especially those having different poses or inconsistent details.*""")with gr.Accordion(label="Generation Settings", open=False):seed = gr.Slider(0, MAX_SEED, label="Seed", value=0, step=1)6 unmodified lineswith gr.Row():slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3.0, step=0.1)slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1)multiimage_algo = gr.Radio(["stochastic", "multidiffusion"], label="Multi-image Algorithm", value="stochastic")generate_btn = gr.Button("Generate")1 unmodified linemesh_simplify = gr.Slider(0.9, 0.98, label="Simplify", value=0.95, step=0.01)texture_size = gr.Slider(512, 2048, label="Texture Size", value=1024, step=512)with gr.Row():extract_glb_btn = gr.Button("Extract GLB", interactive=False)extract_gs_btn = gr.Button("Extract Gaussian", interactive=False)gr.Markdown("""*NOTE: Gaussian file can be very large (~50MB), it will take a while to display and download.*""")with gr.Column():video_output = gr.Video(label="Generated 3D Asset", autoplay=True, loop=True, height=300)model_output = LitModel3D(label="Extracted GLB/Gaussian", exposure=10.0, height=300)with gr.Row():download_glb = gr.DownloadButton(label="Download GLB", interactive=False)download_gs = gr.DownloadButton(label="Download Gaussian", interactive=False)is_multiimage = gr.State(False)output_buf = gr.State()# Example images at the bottom of the pagewith gr.Row() as single_image_example:examples = gr.Examples(examples=[f'assets/example_image/{image}'5 unmodified linesrun_on_click=True,examples_per_page=64,)with gr.Row(visible=False) as multiimage_example:examples_multi = gr.Examples(examples=prepare_multi_example(),inputs=[image_prompt],fn=split_image,outputs=[multiimage_prompt],run_on_click=True,examples_per_page=8,)# Handlersdemo.load(start_session)demo.unload(end_session)single_image_input_tab.select(lambda: tuple([False, gr.Row.update(visible=True), gr.Row.update(visible=False)]),outputs=[is_multiimage, single_image_example, multiimage_example])multiimage_input_tab.select(lambda: tuple([True, gr.Row.update(visible=False), gr.Row.update(visible=True)]),outputs=[is_multiimage, single_image_example, multiimage_example])image_prompt.upload(preprocess_image,inputs=[image_prompt],outputs=[image_prompt],)multiimage_prompt.upload(preprocess_images,inputs=[multiimage_prompt],outputs=[multiimage_prompt],)generate_btn.click(get_seed,1 unmodified lineoutputs=[seed],).then(image_to_3d,inputs=[image_prompt, multiimage_prompt, is_multiimage, seed, ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps, multiimage_algo],outputs=[output_buf, video_output],).then(lambda: tuple([gr.Button(interactive=True), gr.Button(interactive=True)]),outputs=[extract_glb_btn, extract_gs_btn],)video_output.clear(lambda: tuple([gr.Button(interactive=False), gr.Button(interactive=False)]),outputs=[extract_glb_btn, extract_gs_btn],)extract_glb_btn.click(4 unmodified lineslambda: gr.Button(interactive=True),outputs=[download_glb],)extract_gs_btn.click(extract_gaussian,inputs=[output_buf],outputs=[model_output, download_gs],).then(lambda: gr.Button(interactive=True),outputs=[download_gs],)model_output.clear(lambda: gr.Button(interactive=False),
1234276 unmodified lines281282283from typing import *import torchimport torch.nn as nnimport torch.nn.functional as F276 unmodified linescoords = self.sample_sparse_structure(cond, num_samples, sparse_structure_sampler_params)slat = self.sample_slat(cond, coords, slat_sampler_params)return self.decode_slat(slat, formats)12345276 unmodified lines282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376from typing import *from contextlib import contextmanagerimport torchimport torch.nn as nnimport torch.nn.functional as F276 unmodified linescoords = self.sample_sparse_structure(cond, num_samples, sparse_structure_sampler_params)slat = self.sample_slat(cond, coords, slat_sampler_params)return self.decode_slat(slat, formats)@contextmanagerdef inject_sampler_multi_image(self,sampler_name: str,num_images: int,num_steps: int,mode: Literal['stochastic', 'multidiffusion'] = 'stochastic',):"""Inject a sampler with multiple images as condition.Args:sampler_name (str): The name of the sampler to inject.num_images (int): The number of images to condition on.num_steps (int): The number of steps to run the sampler for."""sampler = getattr(self, sampler_name)setattr(sampler, f'_old_inference_model', sampler._inference_model)if mode == 'stochastic':if num_images > num_steps:print(f"\033[93mWarning: number of conditioning images is greater than number of steps for {sampler_name}. ""This may lead to performance degradation.\033[0m")cond_indices = (np.arange(num_steps) % num_images).tolist()def _new_inference_model(self, model, x_t, t, cond, **kwargs):cond_idx = cond_indices.pop(0)cond_i = cond[cond_idx:cond_idx+1]return self._old_inference_model(model, x_t, t, cond=cond_i, **kwargs)elif mode =='multidiffusion':from .samplers import FlowEulerSamplerdef _new_inference_model(self, model, x_t, t, cond, neg_cond, cfg_strength, cfg_interval, **kwargs):if cfg_interval[0] <= t <= cfg_interval[1]:preds = []for i in range(len(cond)):preds.append(FlowEulerSampler._inference_model(self, model, x_t, t, cond[i:i+1], **kwargs))pred = sum(preds) / len(preds)neg_pred = FlowEulerSampler._inference_model(self, model, x_t, t, neg_cond, **kwargs)return (1 + cfg_strength) * pred - cfg_strength * neg_predelse:preds = []for i in range(len(cond)):preds.append(FlowEulerSampler._inference_model(self, model, x_t, t, cond[i:i+1], **kwargs))pred = sum(preds) / len(preds)return predelse:raise ValueError(f"Unsupported mode: {mode}")sampler._inference_model = _new_inference_model.__get__(sampler, type(sampler))yieldsampler._inference_model = sampler._old_inference_modeldelattr(sampler, f'_old_inference_model')@torch.no_grad()def run_multi_image(self,images: List[Image.Image],num_samples: int = 1,seed: int = 42,sparse_structure_sampler_params: dict = {},slat_sampler_params: dict = {},formats: List[str] = ['mesh', 'gaussian', 'radiance_field'],preprocess_image: bool = True,mode: Literal['stochastic', 'multidiffusion'] = 'stochastic',) -> dict:"""Run the pipeline with multiple images as conditionArgs:images (List[Image.Image]): The multi-view images of the assetsnum_samples (int): The number of samples to generate.sparse_structure_sampler_params (dict): Additional parameters for the sparse structure sampler.slat_sampler_params (dict): Additional parameters for the structured latent sampler.preprocess_image (bool): Whether to preprocess the image."""if preprocess_image:images = [self.preprocess_image(image) for image in images]cond = self.get_cond(images)cond['neg_cond'] = cond['neg_cond'][:1]torch.manual_seed(seed)ss_steps = {**self.sparse_structure_sampler_params, **sparse_structure_sampler_params}.get('steps')with self.inject_sampler_multi_image('sparse_structure_sampler', len(images), ss_steps, mode=mode):coords = self.sample_sparse_structure(cond, num_samples, sparse_structure_sampler_params)slat_steps = {**self.slat_sampler_params, **slat_sampler_params}.get('steps')with self.inject_sampler_multi_image('slat_sampler', len(images), slat_steps, mode=mode):slat = self.sample_slat(cond, coords, slat_sampler_params)return self.decode_slat(slat, formats)
1 unmodified line234567112 unmodified lines1201211221231241251261271281291301311321333 unmodified lines13713813914014114214328 unmodified lines1721731741751761771 unmodified lineimport numpy as npfrom plyfile import PlyData, PlyElementfrom .general_utils import inverse_sigmoid, strip_symmetric, build_scaling_rotationclass Gaussian:112 unmodified linesfor i in range(self._rotation.shape[1]):l.append('rot_{}'.format(i))return ldef save_ply(self, path):xyz = self.get_xyz.detach().cpu().numpy()normals = np.zeros_like(xyz)f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()opacities = inverse_sigmoid(self.get_opacity).detach().cpu().numpy()scale = torch.log(self.get_scaling).detach().cpu().numpy()rotation = (self._rotation + self.rots_bias[None, :]).detach().cpu().numpy()dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]3 unmodified linesel = PlyElement.describe(elements, 'vertex')PlyData([el]).write(path)def load_ply(self, path):plydata = PlyData.read(path)xyz = np.stack((np.asarray(plydata.elements[0]["x"]),28 unmodified linesfor idx, attr_name in enumerate(rot_names):rots[:, idx] = np.asarray(plydata.elements[0][attr_name])# convert to actual gaussian attributesxyz = torch.tensor(xyz, dtype=torch.float, device=self.device)features_dc = torch.tensor(features_dc, dtype=torch.float, device=self.device).transpose(1, 2).contiguous()1 unmodified line2345678112 unmodified lines1211221231241251261271281291301311321331341351361371381391401413 unmodified lines14514614714814915015128 unmodified lines1801811821831841851861871881891901911921 unmodified lineimport numpy as npfrom plyfile import PlyData, PlyElementfrom .general_utils import inverse_sigmoid, strip_symmetric, build_scaling_rotationimport utils3dclass Gaussian:112 unmodified linesfor i in range(self._rotation.shape[1]):l.append('rot_{}'.format(i))return ldef save_ply(self, path, transform=[[1, 0, 0], [0, 0, -1], [0, 1, 0]]):xyz = self.get_xyz.detach().cpu().numpy()normals = np.zeros_like(xyz)f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()opacities = inverse_sigmoid(self.get_opacity).detach().cpu().numpy()scale = torch.log(self.get_scaling).detach().cpu().numpy()rotation = (self._rotation + self.rots_bias[None, :]).detach().cpu().numpy()if transform is not None:transform = np.array(transform)xyz = np.matmul(xyz, transform.T)rotation = utils3d.numpy.quaternion_to_matrix(rotation)rotation = np.matmul(transform, rotation)rotation = utils3d.numpy.matrix_to_quaternion(rotation)dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]3 unmodified linesel = PlyElement.describe(elements, 'vertex')PlyData([el]).write(path)def load_ply(self, path, transform=[[1, 0, 0], [0, 0, -1], [0, 1, 0]]):plydata = PlyData.read(path)xyz = np.stack((np.asarray(plydata.elements[0]["x"]),28 unmodified linesfor idx, attr_name in enumerate(rot_names):rots[:, idx] = np.asarray(plydata.elements[0][attr_name])if transform is not None:transform = np.array(transform)xyz = np.matmul(xyz, transform)rotation = utils3d.numpy.quaternion_to_matrix(rotation)rotation = np.matmul(rotation, transform)rotation = utils3d.numpy.matrix_to_quaternion(rotation)# convert to actual gaussian attributesxyz = torch.tensor(xyz, dtype=torch.float, device=self.device)features_dc = torch.tensor(features_dc, dtype=torch.float, device=self.device).transpose(1, 2).contiguous()
13 unmodified lines141516171819434 unmodified lines45445545645745813 unmodified linesfrom PIL import Imagefrom .random_utils import sphere_hammersley_sequencefrom .render_utils import render_multiviewfrom ..representations import Strivec, Gaussian, MeshExtractResult434 unmodified lines# rotate mesh (from z-up to y-up)vertices = vertices @ np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]])mesh = trimesh.Trimesh(vertices, faces, visual=trimesh.visual.TextureVisuals(uv=uvs, image=texture))return mesh13 unmodified lines14151617181920434 unmodified lines45545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658713 unmodified linesfrom PIL import Imagefrom .random_utils import sphere_hammersley_sequencefrom .render_utils import render_multiviewfrom ..renderers import GaussianRendererfrom ..representations import Strivec, Gaussian, MeshExtractResult434 unmodified lines# rotate mesh (from z-up to y-up)vertices = vertices @ np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]])material = trimesh.visual.material.PBRMaterial(roughnessFactor=1.0,baseColorTexture=texture,baseColorFactor=np.array([255, 255, 255, 255], dtype=np.uint8))mesh = trimesh.Trimesh(vertices, faces, visual=trimesh.visual.TextureVisuals(uv=uvs, material=material))return meshdef simplify_gs(gs: Gaussian,simplify: float = 0.95,verbose: bool = True,):"""Simplify 3D GaussiansNOTE: this function is not used in the current implementation for the unsatisfactory performance.Args:gs (Gaussian): 3D Gaussian.simplify (float): Ratio of Gaussians to remove in simplification."""if simplify <= 0:return gs# simplifyobservations, extrinsics, intrinsics = render_multiview(gs, resolution=1024, nviews=100)observations = [torch.tensor(obs / 255.0).float().cuda().permute(2, 0, 1) for obs in observations]# Following https://arxiv.org/pdf/2411.06019renderer = GaussianRenderer({"resolution": 1024,"near": 0.8,"far": 1.6,"ssaa": 1,"bg_color": (0,0,0),})new_gs = Gaussian(**gs.init_params)new_gs._features_dc = gs._features_dc.clone()new_gs._features_rest = gs._features_rest.clone() if gs._features_rest is not None else Nonenew_gs._opacity = torch.nn.Parameter(gs._opacity.clone())new_gs._rotation = torch.nn.Parameter(gs._rotation.clone())new_gs._scaling = torch.nn.Parameter(gs._scaling.clone())new_gs._xyz = torch.nn.Parameter(gs._xyz.clone())start_lr = [1e-4, 1e-3, 5e-3, 0.025]end_lr = [1e-6, 1e-5, 5e-5, 0.00025]optimizer = torch.optim.Adam([{"params": new_gs._xyz, "lr": start_lr[0]},{"params": new_gs._rotation, "lr": start_lr[1]},{"params": new_gs._scaling, "lr": start_lr[2]},{"params": new_gs._opacity, "lr": start_lr[3]},], lr=start_lr[0])def exp_anealing(optimizer, step, total_steps, start_lr, end_lr):return start_lr * (end_lr / start_lr) ** (step / total_steps)def cosine_anealing(optimizer, step, total_steps, start_lr, end_lr):return end_lr + 0.5 * (start_lr - end_lr) * (1 + np.cos(np.pi * step / total_steps))_zeta = new_gs.get_opacity.clone().detach().squeeze()_lambda = torch.zeros_like(_zeta)_delta = 1e-7_interval = 10num_target = int((1 - simplify) * _zeta.shape[0])with tqdm(total=2500, disable=not verbose, desc='Simplifying Gaussian') as pbar:for i in range(2500):# pruneif i % 100 == 0:mask = new_gs.get_opacity.squeeze() > 0.05mask = torch.nonzero(mask).squeeze()new_gs._xyz = torch.nn.Parameter(new_gs._xyz[mask])new_gs._rotation = torch.nn.Parameter(new_gs._rotation[mask])new_gs._scaling = torch.nn.Parameter(new_gs._scaling[mask])new_gs._opacity = torch.nn.Parameter(new_gs._opacity[mask])new_gs._features_dc = new_gs._features_dc[mask]new_gs._features_rest = new_gs._features_rest[mask] if new_gs._features_rest is not None else None_zeta = _zeta[mask]_lambda = _lambda[mask]# update optimizer statefor param_group, new_param in zip(optimizer.param_groups, [new_gs._xyz, new_gs._rotation, new_gs._scaling, new_gs._opacity]):stored_state = optimizer.state[param_group['params'][0]]if 'exp_avg' in stored_state:stored_state['exp_avg'] = stored_state['exp_avg'][mask]stored_state['exp_avg_sq'] = stored_state['exp_avg_sq'][mask]del optimizer.state[param_group['params'][0]]param_group['params'][0] = new_paramoptimizer.state[param_group['params'][0]] = stored_stateopacity = new_gs.get_opacity.squeeze()# sparisfyif i % _interval == 0:_zeta = _lambda + opacity.detach()if opacity.shape[0] > num_target:index = _zeta.topk(num_target)[1]_m = torch.ones_like(_zeta, dtype=torch.bool)_m[index] = 0_zeta[_m] = 0_lambda = _lambda + opacity.detach() - _zeta# sample a random viewview_idx = np.random.randint(len(observations))observation = observations[view_idx]extrinsic = extrinsics[view_idx]intrinsic = intrinsics[view_idx]color = renderer.render(new_gs, extrinsic, intrinsic)['color']rgb_loss = torch.nn.functional.l1_loss(color, observation)loss = rgb_loss + \_delta * torch.sum(torch.pow(_lambda + opacity - _zeta, 2))optimizer.zero_grad()loss.backward()optimizer.step()# update lrfor j in range(len(optimizer.param_groups)):optimizer.param_groups[j]['lr'] = cosine_anealing(optimizer, i, 2500, start_lr[j], end_lr[j])pbar.set_postfix({'loss': rgb_loss.item(), 'num': opacity.shape[0], 'lambda': _lambda.mean().item()})pbar.update()new_gs._xyz = new_gs._xyz.datanew_gs._rotation = new_gs._rotation.datanew_gs._scaling = new_gs._scaling.datanew_gs._opacity = new_gs._opacity.datareturn new_gs
app.py+171-38
assets/example_multi_image/character_1.pngAdded

assets/example_multi_image/character_2.pngAdded

assets/example_multi_image/character_3.pngAdded

assets/example_multi_image/mushroom_1.pngAdded

assets/example_multi_image/mushroom_2.pngAdded

assets/example_multi_image/mushroom_3.pngAdded

assets/example_multi_image/orangeguy_1.pngAdded

assets/example_multi_image/orangeguy_2.pngAdded

assets/example_multi_image/orangeguy_3.pngAdded

assets/example_multi_image/popmart_1.pngAdded

assets/example_multi_image/popmart_2.pngAdded

assets/example_multi_image/popmart_3.pngAdded

assets/example_multi_image/rabbit_1.pngAdded

assets/example_multi_image/rabbit_2.pngAdded

assets/example_multi_image/rabbit_3.pngAdded

assets/example_multi_image/tiger_1.pngAdded

assets/example_multi_image/tiger_2.pngAdded

assets/example_multi_image/tiger_3.pngAdded

assets/example_multi_image/yoimiya_1.pngAdded

assets/example_multi_image/yoimiya_2.pngAdded

assets/example_multi_image/yoimiya_3.pngAdded

trellis/pipelines/trellis_image_to_3d.py+93
trellis/representations/gaussian/gaussian_model.py+18-3
trellis/utils/postprocessing_utils.py+130-1