Image-to-3D
Hunyuan3D-2
Diffusers
Safetensors
English
Chinese
text-to-3d
Huiwenshi commited on
Commit
24d16fc
·
verified ·
1 Parent(s): 69b88e2

Upload hy3dpaint/textureGenPipeline.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. hy3dpaint/textureGenPipeline.py +192 -0
hy3dpaint/textureGenPipeline.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
2
+ # except for the third-party components listed below.
3
+ # Hunyuan 3D does not impose any additional limitations beyond what is outlined
4
+ # in the repsective licenses of these third-party components.
5
+ # Users must comply with all terms and conditions of original licenses of these third-party
6
+ # components and must ensure that the usage of the third party components adheres to
7
+ # all relevant laws and regulations.
8
+
9
+ # For avoidance of doubts, Hunyuan 3D means the large language models and
10
+ # their software and algorithms, including trained model weights, parameters (including
11
+ # optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
12
+ # fine-tuning enabling code and other elements of the foregoing made publicly available
13
+ # by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
14
+
15
+ import os
16
+ import torch
17
+ import copy
18
+ import trimesh
19
+ import numpy as np
20
+ from PIL import Image
21
+ from typing import List
22
+ from DifferentiableRenderer.MeshRender import MeshRender
23
+ from utils.simplify_mesh_utils import remesh_mesh
24
+ from utils.multiview_utils import multiviewDiffusionNet
25
+ from utils.pipeline_utils import ViewProcessor
26
+ from utils.image_super_utils import imageSuperNet
27
+ from utils.uvwrap_utils import mesh_uv_wrap
28
+ from DifferentiableRenderer.mesh_utils import convert_obj_to_glb
29
+ import warnings
30
+
31
+ warnings.filterwarnings("ignore")
32
+ from diffusers.utils import logging as diffusers_logging
33
+
34
+ diffusers_logging.set_verbosity(50)
35
+
36
+
37
+ class Hunyuan3DPaintConfig:
38
+ def __init__(self, max_num_view, resolution):
39
+ self.device = "cuda"
40
+
41
+ self.multiview_cfg_path = "cfgs/hunyuan-paint-pbr.yaml"
42
+ self.custom_pipeline = "hunyuanpaintpbr"
43
+ self.multiview_pretrained_path = "tencent/Hunyuan3D-2.1"
44
+ self.dino_ckpt_path = "facebook/dinov2-giant"
45
+ self.realesrgan_ckpt_path = "ckpt/RealESRGAN_x4plus.pth"
46
+
47
+ self.raster_mode = "cr"
48
+ self.bake_mode = "back_sample"
49
+ self.render_size = 1024 * 2
50
+ self.texture_size = 1024 * 4
51
+ self.max_selected_view_num = max_num_view
52
+ self.resolution = resolution
53
+ self.bake_exp = 4
54
+ self.merge_method = "fast"
55
+
56
+ # view selection
57
+ self.candidate_camera_azims = [0, 90, 180, 270, 0, 180]
58
+ self.candidate_camera_elevs = [0, 0, 0, 0, 90, -90]
59
+ self.candidate_view_weights = [1, 0.1, 0.5, 0.1, 0.05, 0.05]
60
+
61
+ for azim in range(0, 360, 30):
62
+ self.candidate_camera_azims.append(azim)
63
+ self.candidate_camera_elevs.append(20)
64
+ self.candidate_view_weights.append(0.01)
65
+
66
+ self.candidate_camera_azims.append(azim)
67
+ self.candidate_camera_elevs.append(-20)
68
+ self.candidate_view_weights.append(0.01)
69
+
70
+
71
+ class Hunyuan3DPaintPipeline:
72
+
73
+ def __init__(self, config=None) -> None:
74
+ self.config = config if config is not None else Hunyuan3DPaintConfig()
75
+ self.models = {}
76
+ self.stats_logs = {}
77
+ self.render = MeshRender(
78
+ default_resolution=self.config.render_size,
79
+ texture_size=self.config.texture_size,
80
+ bake_mode=self.config.bake_mode,
81
+ raster_mode=self.config.raster_mode,
82
+ )
83
+ self.view_processor = ViewProcessor(self.config, self.render)
84
+ self.load_models()
85
+
86
+ def load_models(self):
87
+ torch.cuda.empty_cache()
88
+ self.models["super_model"] = imageSuperNet(self.config)
89
+ self.models["multiview_model"] = multiviewDiffusionNet(self.config)
90
+ print("Models Loaded.")
91
+
92
+ @torch.no_grad()
93
+ def __call__(self, mesh_path=None, image_path=None, output_mesh_path=None, use_remesh=True, save_glb=True):
94
+ """Generate texture for 3D mesh using multiview diffusion"""
95
+ # Ensure image_prompt is a list
96
+ if isinstance(image_path, str):
97
+ image_prompt = Image.open(image_path)
98
+ elif isinstance(image_path, Image.Image):
99
+ image_prompt = image_path
100
+ if not isinstance(image_prompt, List):
101
+ image_prompt = [image_prompt]
102
+ else:
103
+ image_prompt = image_path
104
+
105
+ # Process mesh
106
+ path = os.path.dirname(mesh_path)
107
+ if use_remesh:
108
+ processed_mesh_path = os.path.join(path, "white_mesh_remesh.obj")
109
+ remesh_mesh(mesh_path, processed_mesh_path)
110
+ else:
111
+ processed_mesh_path = mesh_path
112
+
113
+ # Output path
114
+ if output_mesh_path is None:
115
+ output_mesh_path = os.path.join(path, f"textured_mesh.obj")
116
+
117
+ # Load mesh
118
+ mesh = trimesh.load(processed_mesh_path)
119
+ mesh = mesh_uv_wrap(mesh)
120
+ self.render.load_mesh(mesh=mesh)
121
+
122
+ ########### View Selection #########
123
+ selected_camera_elevs, selected_camera_azims, selected_view_weights = self.view_processor.bake_view_selection(
124
+ self.config.candidate_camera_elevs,
125
+ self.config.candidate_camera_azims,
126
+ self.config.candidate_view_weights,
127
+ self.config.max_selected_view_num,
128
+ )
129
+
130
+ normal_maps = self.view_processor.render_normal_multiview(
131
+ selected_camera_elevs, selected_camera_azims, use_abs_coor=True
132
+ )
133
+ position_maps = self.view_processor.render_position_multiview(selected_camera_elevs, selected_camera_azims)
134
+
135
+ ########## Style ###########
136
+ image_caption = "high quality"
137
+ image_style = []
138
+ for image in image_prompt:
139
+ image = image.resize((512, 512))
140
+ if image.mode == "RGBA":
141
+ white_bg = Image.new("RGB", image.size, (255, 255, 255))
142
+ white_bg.paste(image, mask=image.getchannel("A"))
143
+ image = white_bg
144
+ image_style.append(image)
145
+ image_style = [image.convert("RGB") for image in image_style]
146
+
147
+ ########### Multiview ##########
148
+ multiviews_pbr = self.models["multiview_model"](
149
+ image_style,
150
+ normal_maps + position_maps,
151
+ prompt=image_caption,
152
+ custom_view_size=self.config.resolution,
153
+ resize_input=True,
154
+ )
155
+ ########### Enhance ##########
156
+ enhance_images = {}
157
+ enhance_images["albedo"] = copy.deepcopy(multiviews_pbr["albedo"])
158
+ enhance_images["mr"] = copy.deepcopy(multiviews_pbr["mr"])
159
+
160
+ for i in range(len(enhance_images["albedo"])):
161
+ enhance_images["albedo"][i] = self.models["super_model"](enhance_images["albedo"][i])
162
+ enhance_images["mr"][i] = self.models["super_model"](enhance_images["mr"][i])
163
+
164
+ ########### Bake ##########
165
+ for i in range(len(enhance_images)):
166
+ enhance_images["albedo"][i] = enhance_images["albedo"][i].resize(
167
+ (self.config.render_size, self.config.render_size)
168
+ )
169
+ enhance_images["mr"][i] = enhance_images["mr"][i].resize((self.config.render_size, self.config.render_size))
170
+ texture, mask = self.view_processor.bake_from_multiview(
171
+ enhance_images["albedo"], selected_camera_elevs, selected_camera_azims, selected_view_weights
172
+ )
173
+ mask_np = (mask.squeeze(-1).cpu().numpy() * 255).astype(np.uint8)
174
+ texture_mr, mask_mr = self.view_processor.bake_from_multiview(
175
+ enhance_images["mr"], selected_camera_elevs, selected_camera_azims, selected_view_weights
176
+ )
177
+ mask_mr_np = (mask_mr.squeeze(-1).cpu().numpy() * 255).astype(np.uint8)
178
+
179
+ ########## inpaint ###########
180
+ texture = self.view_processor.texture_inpaint(texture, mask_np)
181
+ self.render.set_texture(texture, force_set=True)
182
+ if "mr" in enhance_images:
183
+ texture_mr = self.view_processor.texture_inpaint(texture_mr, mask_mr_np)
184
+ self.render.set_texture_mr(texture_mr)
185
+
186
+ self.render.save_mesh(output_mesh_path, downsample=True)
187
+
188
+ if save_glb:
189
+ convert_obj_to_glb(output_mesh_path, output_mesh_path.replace(".obj", ".glb"))
190
+ output_glb_path = output_mesh_path.replace(".obj", ".glb")
191
+
192
+ return output_mesh_path