lemonaddie commited on
Commit
b6ddde2
1 Parent(s): e82b0fa

Delete models/depth_pipeline.py

Browse files
Files changed (1) hide show
  1. models/depth_pipeline.py +0 -310
models/depth_pipeline.py DELETED
@@ -1,310 +0,0 @@
1
- # A reimplemented version in public environments by Xiao Fu and Mu Hu
2
-
3
- from typing import Any, Dict, Union
4
-
5
- import torch
6
- from torch.utils.data import DataLoader, TensorDataset
7
- import numpy as np
8
- from tqdm.auto import tqdm
9
- from PIL import Image
10
- from diffusers import (
11
- DiffusionPipeline,
12
- DDIMScheduler,
13
- UNet2DConditionModel,
14
- AutoencoderKL,
15
- )
16
- from diffusers.utils import BaseOutput
17
- from transformers import CLIPTextModel, CLIPTokenizer
18
-
19
- from utils.image_util import resize_max_res,chw2hwc,colorize_depth_maps
20
- from utils.colormap import kitti_colormap
21
- from utils.depth_ensemble import ensemble_depths
22
- from utils.batch_size import find_batch_size
23
- import cv2
24
-
25
- class DepthPipelineOutput(BaseOutput):
26
- """
27
- Output class for Marigold monocular depth prediction pipeline.
28
-
29
- Args:
30
- depth_np (`np.ndarray`):
31
- Predicted depth map, with depth values in the range of [0, 1].
32
- depth_colored (`PIL.Image.Image`):
33
- Colorized depth map, with the shape of [3, H, W] and values in [0, 1].
34
- uncertainty (`None` or `np.ndarray`):
35
- Uncalibrated uncertainty(MAD, median absolute deviation) coming from ensembling.
36
- """
37
- depth_np: np.ndarray
38
- depth_colored: Image.Image
39
- uncertainty: Union[None, np.ndarray]
40
-
41
- class DepthEstimationPipeline(DiffusionPipeline):
42
- # two hyper-parameters
43
- latent_scale_factor = 0.18215
44
-
45
- def __init__(self,
46
- unet:UNet2DConditionModel,
47
- vae:AutoencoderKL,
48
- scheduler:DDIMScheduler,
49
- text_encoder:CLIPTextModel,
50
- tokenizer:CLIPTokenizer,
51
- ):
52
- super().__init__()
53
-
54
- self.register_modules(
55
- unet=unet,
56
- vae=vae,
57
- scheduler=scheduler,
58
- text_encoder=text_encoder,
59
- tokenizer=tokenizer,
60
- )
61
- self.empty_text_embed = None
62
-
63
- @torch.no_grad()
64
- def __call__(self,
65
- input_image:Image,
66
- denosing_steps: int =10,
67
- ensemble_size: int =10,
68
- processing_res: int = 768,
69
- match_input_res:bool =True,
70
- batch_size:int = 0,
71
- color_map: str="Spectral",
72
- show_progress_bar:bool = True,
73
- ensemble_kwargs: Dict = None,
74
- ) -> DepthPipelineOutput:
75
-
76
- # inherit from thea Diffusion Pipeline
77
- device = self.device
78
- input_size = input_image.size
79
-
80
- # adjust the input resolution.
81
- if not match_input_res:
82
- assert (
83
- processing_res is not None
84
- )," Value Error: `resize_output_back` is only valid with "
85
-
86
- assert processing_res >=0
87
- assert denosing_steps >=1
88
- assert ensemble_size >=1
89
-
90
- # --------------- Image Processing ------------------------
91
- # Resize image
92
- if processing_res >0:
93
- input_image = resize_max_res(
94
- input_image, max_edge_resolution=processing_res
95
- ) # resize image: for kitti is 231, 768
96
-
97
- # Convert the image to RGB, to 1. reomve the alpha channel.
98
- input_image = input_image.convert("RGB")
99
- image = np.array(input_image)
100
-
101
- # Normalize RGB Values.
102
- rgb = np.transpose(image,(2,0,1))
103
- rgb_norm = rgb / 255.0 * 2.0 - 1.0 # [0, 255] -> [-1, 1]
104
- rgb_norm = torch.from_numpy(rgb_norm).to(self.dtype)
105
- rgb_norm = rgb_norm.to(device)
106
-
107
- assert rgb_norm.min() >= -1.0 and rgb_norm.max() <= 1.0
108
-
109
- # ----------------- predicting depth -----------------
110
- duplicated_rgb = torch.stack([rgb_norm] * ensemble_size)
111
- single_rgb_dataset = TensorDataset(duplicated_rgb)
112
-
113
- # find the batch size
114
- if batch_size>0:
115
- _bs = batch_size
116
- else:
117
- _bs = 1
118
-
119
- single_rgb_loader = DataLoader(single_rgb_dataset, batch_size=_bs, shuffle=False)
120
-
121
- # predicted the depth
122
- depth_pred_ls = []
123
-
124
- if show_progress_bar:
125
- iterable_bar = tqdm(
126
- single_rgb_loader, desc=" " * 2 + "Inference batches", leave=False
127
- )
128
- else:
129
- iterable_bar = single_rgb_loader
130
-
131
- for batch in iterable_bar:
132
- (batched_image, )= batch # here the image is still around 0-1
133
-
134
- depth_pred_raw = self.single_infer(
135
- input_rgb=batched_image,
136
- num_inference_steps=denosing_steps,
137
- show_pbar=show_progress_bar,
138
- )
139
- depth_pred_ls.append(depth_pred_raw.detach().clone())
140
-
141
- depth_preds = torch.concat(depth_pred_ls, axis=0).squeeze() #(10,224,768)
142
- torch.cuda.empty_cache() # clear vram cache for ensembling
143
-
144
- # ----------------- Test-time ensembling -----------------
145
- if ensemble_size > 1:
146
- depth_pred, pred_uncert = ensemble_depths(
147
- depth_preds, **(ensemble_kwargs or {})
148
- )
149
- else:
150
- depth_pred = depth_preds
151
- pred_uncert = None
152
-
153
- # ----------------- Post processing -----------------
154
- # Scale prediction to [0, 1]
155
- min_d = torch.min(depth_pred)
156
- max_d = torch.max(depth_pred)
157
- depth_pred = (depth_pred - min_d) / (max_d - min_d)
158
-
159
- # Convert to numpy
160
- depth_pred = depth_pred.cpu().numpy().astype(np.float32)
161
-
162
- # Resize back to original resolution
163
- if match_input_res:
164
- pred_img = Image.fromarray(depth_pred)
165
- pred_img = pred_img.resize(input_size)
166
- depth_pred = np.asarray(pred_img)
167
-
168
- # Clip output range: current size is the original size
169
- depth_pred = depth_pred.clip(0, 1)
170
-
171
- # colorization using the KITTI Color Plan.
172
- depth_pred_vis = depth_pred * 70
173
- disp_vis = 400/(depth_pred_vis+1e-3)
174
- disp_vis = disp_vis.clip(0,500)
175
-
176
- depth_color_pred = kitti_colormap(disp_vis)
177
-
178
- # Colorize
179
- depth_colored = colorize_depth_maps(
180
- depth_pred, 0, 1, cmap=color_map
181
- ).squeeze() # [3, H, W], value in (0, 1)
182
- depth_colored = (depth_colored * 255).astype(np.uint8)
183
- depth_colored_hwc = chw2hwc(depth_colored)
184
- depth_colored_img = Image.fromarray(depth_colored_hwc)
185
-
186
- return DepthPipelineOutput(
187
- depth_np = depth_pred,
188
- depth_colored = depth_colored_img,
189
- uncertainty=pred_uncert,
190
- )
191
-
192
- def __encode_empty_text(self):
193
- """
194
- Encode text embedding for empty prompt
195
- """
196
- prompt = ""
197
- text_inputs = self.tokenizer(
198
- prompt,
199
- padding="do_not_pad",
200
- max_length=self.tokenizer.model_max_length,
201
- truncation=True,
202
- return_tensors="pt",
203
- )
204
- text_input_ids = text_inputs.input_ids.to(self.text_encoder.device) #[1,2]
205
- # print(text_input_ids.shape)
206
- self.empty_text_embed = self.text_encoder(text_input_ids)[0].to(self.dtype) #[1,2,1024]
207
-
208
-
209
- @torch.no_grad()
210
- def single_infer(self,input_rgb:torch.Tensor,
211
- num_inference_steps:int,
212
- show_pbar:bool,):
213
-
214
- device = input_rgb.device
215
-
216
- # Set timesteps: inherit from the diffuison pipeline
217
- self.scheduler.set_timesteps(num_inference_steps, device=device) # here the numbers of the steps is only 10.
218
- timesteps = self.scheduler.timesteps # [T]
219
-
220
- # encode image
221
- rgb_latent = self.encode_RGB(input_rgb) # 1/8 Resolution with a channel nums of 4.
222
-
223
- # Initial depth map (Guassian noise)
224
- depth_latent = torch.randn(rgb_latent.shape, device=device, dtype=self.dtype) # [B, 4, H/8, W/8]
225
-
226
- # Batched empty text embedding
227
- if self.empty_text_embed is None:
228
- self.__encode_empty_text()
229
-
230
- batch_empty_text_embed = self.empty_text_embed.repeat(
231
- (rgb_latent.shape[0], 1, 1)
232
- ) # [B, 2, 1024]
233
-
234
-
235
- # Denoising loop
236
- if show_pbar:
237
- iterable = tqdm(
238
- enumerate(timesteps),
239
- total=len(timesteps),
240
- leave=False,
241
- desc=" " * 4 + "Diffusion denoising",
242
- )
243
- else:
244
- iterable = enumerate(timesteps)
245
-
246
- for i, t in iterable:
247
- unet_input = torch.cat([rgb_latent, depth_latent], dim=1)
248
-
249
- # predict the noise residual
250
- noise_pred = self.unet(
251
- unet_input, t, encoder_hidden_states=batch_empty_text_embed
252
- ).sample # [B, 4, h, w]
253
-
254
- # compute the previous noisy sample x_t -> x_t-1
255
- depth_latent = self.scheduler.step(noise_pred, t, depth_latent).prev_sample
256
-
257
- torch.cuda.empty_cache()
258
-
259
- depth = self.decode_depth(depth_latent)
260
-
261
- depth = torch.clip(depth, -1.0, 1.0)
262
- depth = (depth + 1.0) / 2.0
263
-
264
- return depth
265
-
266
-
267
- def encode_RGB(self, rgb_in: torch.Tensor) -> torch.Tensor:
268
- """
269
- Encode RGB image into latent.
270
-
271
- Args:
272
- rgb_in (`torch.Tensor`):
273
- Input RGB image to be encoded.
274
-
275
- Returns:
276
- `torch.Tensor`: Image latent.
277
- """
278
-
279
- # encode
280
- h = self.vae.encoder(rgb_in)
281
-
282
- moments = self.vae.quant_conv(h)
283
- mean, logvar = torch.chunk(moments, 2, dim=1)
284
- # scale latent
285
- rgb_latent = mean * self.latent_scale_factor
286
-
287
- return rgb_latent
288
-
289
- def decode_depth(self, depth_latent: torch.Tensor) -> torch.Tensor:
290
- """
291
- Decode depth latent into depth map.
292
-
293
- Args:
294
- depth_latent (`torch.Tensor`):
295
- Depth latent to be decoded.
296
-
297
- Returns:
298
- `torch.Tensor`: Decoded depth map.
299
- """
300
-
301
- # scale latent
302
- depth_latent = depth_latent / self.latent_scale_factor
303
- # decode
304
- z = self.vae.post_quant_conv(depth_latent)
305
- stacked = self.vae.decoder(z)
306
- # mean of output channels
307
-
308
- depth_mean = stacked.mean(dim=1, keepdim=True)
309
- return depth_mean
310
-