wyysf commited on
Commit
c5f7475
β€’
1 Parent(s): a71c535

Upload app.py

Browse files
Files changed (1) hide show
  1. apps/third_party/CRM/app.py +228 -0
apps/third_party/CRM/app.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Not ready to use yet
2
+ import argparse
3
+ import numpy as np
4
+ import gradio as gr
5
+ from omegaconf import OmegaConf
6
+ import torch
7
+ from PIL import Image
8
+ import PIL
9
+ from pipelines import TwoStagePipeline
10
+ from huggingface_hub import hf_hub_download
11
+ import os
12
+ import rembg
13
+ from typing import Any
14
+ import json
15
+ import os
16
+ import json
17
+ import argparse
18
+
19
+ from model import CRM
20
+ from inference import generate3d
21
+
22
+ pipeline = None
23
+ rembg_session = rembg.new_session()
24
+
25
+
26
+ def expand_to_square(image, bg_color=(0, 0, 0, 0)):
27
+ # expand image to 1:1
28
+ width, height = image.size
29
+ if width == height:
30
+ return image
31
+ new_size = (max(width, height), max(width, height))
32
+ new_image = Image.new("RGBA", new_size, bg_color)
33
+ paste_position = ((new_size[0] - width) // 2, (new_size[1] - height) // 2)
34
+ new_image.paste(image, paste_position)
35
+ return new_image
36
+
37
+ def check_input_image(input_image):
38
+ if input_image is None:
39
+ raise gr.Error("No image uploaded!")
40
+
41
+
42
+ def remove_background(
43
+ image: PIL.Image.Image,
44
+ rembg_session = None,
45
+ force: bool = False,
46
+ **rembg_kwargs,
47
+ ) -> PIL.Image.Image:
48
+ do_remove = True
49
+ if image.mode == "RGBA" and image.getextrema()[3][0] < 255:
50
+ # explain why current do not rm bg
51
+ print("alhpa channl not enpty, skip remove background, using alpha channel as mask")
52
+ background = Image.new("RGBA", image.size, (0, 0, 0, 0))
53
+ image = Image.alpha_composite(background, image)
54
+ do_remove = False
55
+ do_remove = do_remove or force
56
+ if do_remove:
57
+ image = rembg.remove(image, session=rembg_session, **rembg_kwargs)
58
+ return image
59
+
60
+ def do_resize_content(original_image: Image, scale_rate):
61
+ # resize image content wile retain the original image size
62
+ if scale_rate != 1:
63
+ # Calculate the new size after rescaling
64
+ new_size = tuple(int(dim * scale_rate) for dim in original_image.size)
65
+ # Resize the image while maintaining the aspect ratio
66
+ resized_image = original_image.resize(new_size)
67
+ # Create a new image with the original size and black background
68
+ padded_image = Image.new("RGBA", original_image.size, (0, 0, 0, 0))
69
+ paste_position = ((original_image.width - resized_image.width) // 2, (original_image.height - resized_image.height) // 2)
70
+ padded_image.paste(resized_image, paste_position)
71
+ return padded_image
72
+ else:
73
+ return original_image
74
+
75
+ def add_background(image, bg_color=(255, 255, 255)):
76
+ # given an RGBA image, alpha channel is used as mask to add background color
77
+ background = Image.new("RGBA", image.size, bg_color)
78
+ return Image.alpha_composite(background, image)
79
+
80
+
81
+ def preprocess_image(image, background_choice, foreground_ratio, backgroud_color):
82
+ """
83
+ input image is a pil image in RGBA, return RGB image
84
+ """
85
+ print(background_choice)
86
+ if background_choice == "Alpha as mask":
87
+ background = Image.new("RGBA", image.size, (0, 0, 0, 0))
88
+ image = Image.alpha_composite(background, image)
89
+ else:
90
+ image = remove_background(image, rembg_session, force_remove=True)
91
+ image = do_resize_content(image, foreground_ratio)
92
+ image = expand_to_square(image)
93
+ image = add_background(image, backgroud_color)
94
+ return image.convert("RGB")
95
+
96
+
97
+ def gen_image(input_image, seed, scale, step):
98
+ global pipeline, model, args
99
+ pipeline.set_seed(seed)
100
+ rt_dict = pipeline(input_image, scale=scale, step=step)
101
+ stage1_images = rt_dict["stage1_images"]
102
+ stage2_images = rt_dict["stage2_images"]
103
+ np_imgs = np.concatenate(stage1_images, 1)
104
+ np_xyzs = np.concatenate(stage2_images, 1)
105
+
106
+ glb_path, obj_path = generate3d(model, np_imgs, np_xyzs, args.device)
107
+ return Image.fromarray(np_imgs), Image.fromarray(np_xyzs), glb_path, obj_path
108
+
109
+
110
+ parser = argparse.ArgumentParser()
111
+ parser.add_argument(
112
+ "--stage1_config",
113
+ type=str,
114
+ default="configs/nf7_v3_SNR_rd_size_stroke.yaml",
115
+ help="config for stage1",
116
+ )
117
+ parser.add_argument(
118
+ "--stage2_config",
119
+ type=str,
120
+ default="configs/stage2-v2-snr.yaml",
121
+ help="config for stage2",
122
+ )
123
+
124
+ parser.add_argument("--device", type=str, default="cuda")
125
+ args = parser.parse_args()
126
+
127
+ crm_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="CRM.pth")
128
+ specs = json.load(open("configs/specs_objaverse_total.json"))
129
+ model = CRM(specs).to(args.device)
130
+ model.load_state_dict(torch.load(crm_path, map_location = args.device), strict=False)
131
+
132
+ stage1_config = OmegaConf.load(args.stage1_config).config
133
+ stage2_config = OmegaConf.load(args.stage2_config).config
134
+ stage2_sampler_config = stage2_config.sampler
135
+ stage1_sampler_config = stage1_config.sampler
136
+
137
+ stage1_model_config = stage1_config.models
138
+ stage2_model_config = stage2_config.models
139
+
140
+ xyz_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="ccm-diffusion.pth")
141
+ pixel_path = hf_hub_download(repo_id="Zhengyi/CRM", filename="pixel-diffusion.pth")
142
+ stage1_model_config.resume = pixel_path
143
+ stage2_model_config.resume = xyz_path
144
+
145
+ pipeline = TwoStagePipeline(
146
+ stage1_model_config,
147
+ stage2_model_config,
148
+ stage1_sampler_config,
149
+ stage2_sampler_config,
150
+ device=args.device,
151
+ dtype=torch.float16
152
+ )
153
+
154
+ with gr.Blocks() as demo:
155
+ gr.Markdown("# CRM: Single Image to 3D Textured Mesh with Convolutional Reconstruction Model")
156
+ with gr.Row():
157
+ with gr.Column():
158
+ with gr.Row():
159
+ image_input = gr.Image(
160
+ label="Image input",
161
+ image_mode="RGBA",
162
+ sources="upload",
163
+ type="pil",
164
+ )
165
+ processed_image = gr.Image(label="Processed Image", interactive=False, type="pil", image_mode="RGB")
166
+ with gr.Row():
167
+ with gr.Column():
168
+ with gr.Row():
169
+ background_choice = gr.Radio([
170
+ "Alpha as mask",
171
+ "Auto Remove background"
172
+ ], value="Auto Remove background",
173
+ label="backgroud choice")
174
+ # do_remove_background = gr.Checkbox(label=, value=True)
175
+ # force_remove = gr.Checkbox(label=, value=False)
176
+ back_groud_color = gr.ColorPicker(label="Background Color", value="#7F7F7F", interactive=False)
177
+ foreground_ratio = gr.Slider(
178
+ label="Foreground Ratio",
179
+ minimum=0.5,
180
+ maximum=1.0,
181
+ value=1.0,
182
+ step=0.05,
183
+ )
184
+
185
+ with gr.Column():
186
+ seed = gr.Number(value=1234, label="seed", precision=0)
187
+ guidance_scale = gr.Number(value=5.5, minimum=3, maximum=10, label="guidance_scale")
188
+ step = gr.Number(value=50, minimum=30, maximum=100, label="sample steps", precision=0)
189
+ text_button = gr.Button("Generate 3D shape")
190
+ gr.Examples(
191
+ examples=[os.path.join("examples", i) for i in os.listdir("examples")],
192
+ inputs=[image_input],
193
+ )
194
+ with gr.Column():
195
+ image_output = gr.Image(interactive=False, label="Output RGB image")
196
+ xyz_ouput = gr.Image(interactive=False, label="Output CCM image")
197
+
198
+ output_model = gr.Model3D(
199
+ label="Output GLB",
200
+ interactive=False,
201
+ )
202
+ gr.Markdown("Note: The GLB model shown here has a darker lighting and enlarged UV seams. Download for correct results.")
203
+ output_obj = gr.File(interactive=False, label="Output OBJ")
204
+
205
+ inputs = [
206
+ processed_image,
207
+ seed,
208
+ guidance_scale,
209
+ step,
210
+ ]
211
+ outputs = [
212
+ image_output,
213
+ xyz_ouput,
214
+ output_model,
215
+ output_obj,
216
+ ]
217
+
218
+
219
+ text_button.click(fn=check_input_image, inputs=[image_input]).success(
220
+ fn=preprocess_image,
221
+ inputs=[image_input, background_choice, foreground_ratio, back_groud_color],
222
+ outputs=[processed_image],
223
+ ).success(
224
+ fn=gen_image,
225
+ inputs=inputs,
226
+ outputs=outputs,
227
+ )
228
+ demo.queue().launch()