1pip install -q numpy pillow torch torchvision
2pip install -q git+https://github.com/geetu040/transformers.git@depth-pro-projects#egg=transformers
1import requests
2from PIL import Image
3import torch
4from huggingface_hub import hf_hub_download
5import matplotlib.pyplot as plt
6
7# custom installation from this PR: https://github.com/huggingface/transformers/pull/34583
8# !pip install git+https://github.com/geetu040/transformers.git@depth-pro-projects#egg=transformers
9from transformers import DepthProConfig, DepthProImageProcessorFast, DepthProForDepthEstimation
1# load DepthPro model, used as backbone
2config = DepthProConfig(
3 patch_size=32,
4 patch_embeddings_size=4,
5 num_hidden_layers=12,
6 intermediate_hook_ids=[11, 8, 7, 5],
7 intermediate_feature_dims=[256, 256, 256, 256],
8 scaled_images_ratios=[0.5, 1.0],
9 scaled_images_overlap_ratios=[0.5, 0.25],
10 scaled_images_feature_dims=[1024, 512],
11 use_fov_model=False,
12)
13depthpro_for_depth_estimation = DepthProForDepthEstimation(config)
1# create DepthPro for super resolution
2class DepthProForSuperResolution(torch.nn.Module):
3 def __init__(self, depthpro_for_depth_estimation):
4 super().__init__()
5
6 self.depthpro_for_depth_estimation = depthpro_for_depth_estimation
7 hidden_size = self.depthpro_for_depth_estimation.config.fusion_hidden_size
8
9 self.image_head = torch.nn.Sequential(
10 torch.nn.ConvTranspose2d(
11 in_channels=config.num_channels,
12 out_channels=hidden_size,
13 kernel_size=4, stride=2, padding=1
14 ),
15 torch.nn.ReLU(),
16 )
17
18 self.head = torch.nn.Sequential(
19 torch.nn.Conv2d(
20 in_channels=hidden_size,
21 out_channels=hidden_size,
22 kernel_size=3, stride=1, padding=1
23 ),
24 torch.nn.ReLU(),
25 torch.nn.ConvTranspose2d(
26 in_channels=hidden_size,
27 out_channels=hidden_size,
28 kernel_size=4, stride=2, padding=1
29 ),
30 torch.nn.ReLU(),
31 torch.nn.Conv2d(
32 in_channels=hidden_size,
33 out_channels=self.depthpro_for_depth_estimation.config.num_channels,
34 kernel_size=3, stride=1, padding=1
35 ),
36 )
37
38 def forward(self, pixel_values):
39 # x is the low resolution image
40 x = pixel_values
41 encoder_features = self.depthpro_for_depth_estimation.depth_pro(x).features
42 fused_hidden_state = self.depthpro_for_depth_estimation.fusion_stage(encoder_features)[-1]
43 x = self.image_head(x)
44 x = torch.nn.functional.interpolate(x, size=fused_hidden_state.shape[2:])
45 x = x + fused_hidden_state
46 x = self.head(x)
47 return x
1# initialize the model
2model = DepthProForSuperResolution(depthpro_for_depth_estimation)
3device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
4model = model.to(device)
5
6# load weights
7weights_path = hf_hub_download(repo_id="geetu040/DepthPro_SR_4x_256p", filename="model_weights.pth")
8model.load_state_dict(torch.load(weights_path, map_location=torch.device('cpu')))
9
10# load image processor
11image_processor = DepthProImageProcessorFast(
12 do_resize=False,
13 do_rescale=True,
14 do_normalize=True
15)
1# inference
2
3url = "https://huggingface.co/spaces/geetu040/DepthPro_SR_4x_256p/resolve/main/assets/examples/man_with_arms_open.jpeg"
4
5image = Image.open(requests.get(url, stream=True).raw)
6image.thumbnail((256, 256)) # resizes the image object to fit within a 256x256 pixel box
7
8# prepare image for the model
9inputs = image_processor(images=image, return_tensors="pt")
10inputs = {k: v.to(device) for k, v in inputs.items()}
11
12with torch.no_grad():
13 outputs = model(**inputs)
14
15# convert tensors to PIL.Image
16output = outputs[0] # extract the first and only batch
17output = output.cpu() # unload from cuda if used
18output = torch.permute(output, (1, 2, 0)) # (C, H, W) -> (H, W, C)
19output = output * 0.5 + 0.5 # undo normalization
20output = output * 255. # undo scaling
21output = output.clip(0, 255.) # fix out of range
22output = output.numpy() # convert to numpy
23output = output.astype('uint8') # convert to PIL.Image compatible format
24output = Image.fromarray(output) # create PIL.Image object
25
26# visualize the prediction
27fig, axes = plt.subplots(1, 2, figsize=(20, 20))
28axes[0].imshow(image)
29axes[0].set_title(f'Low-Resolution (LR) {image.size}')
30axes[0].axis('off')
31axes[1].imshow(output)
32axes[1].set_title(f'Super-Resolution (SR) {output.size}')
33axes[1].axis('off')
34plt.subplots_adjust(wspace=0, hspace=0)
35plt.show()