huntrezz commited on
Commit
d5bc6d9
·
verified ·
1 Parent(s): 9381f5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -33
app.py CHANGED
@@ -1,41 +1,53 @@
1
  import cv2
2
  import torch
3
  import numpy as np
4
- from transformers import DPTForDepthEstimation, DPTImageProcessor
5
  import gradio as gr
6
- import torch.nn.utils.prune as prune
7
  import matplotlib.pyplot as plt
8
  from mpl_toolkits.mplot3d import Axes3D
9
 
10
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
 
12
- model = DPTForDepthEstimation.from_pretrained("Intel/dpt-swinv2-tiny-256", torch_dtype=torch.float32)
13
- model.eval()
14
-
15
- # Apply global unstructured pruning
16
- parameters_to_prune = [
17
- (module, "weight") for module in filter(lambda m: isinstance(m, (torch.nn.Conv2d, torch.nn.Linear)), model.modules())
18
- ]
19
- prune.global_unstructured(
20
- parameters_to_prune,
21
- pruning_method=prune.L1Unstructured,
22
- amount=0.2, # Prune 20% of weights
23
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- for module, _ in parameters_to_prune:
26
- prune.remove(module, "weight")
 
 
27
 
28
- model = torch.quantization.quantize_dynamic(
29
- model, {torch.nn.Linear, torch.nn.Conv2d}, dtype=torch.qint8
30
- )
31
-
32
- model = model.to(device)
33
 
34
  processor = DPTImageProcessor.from_pretrained("Intel/dpt-swinv2-tiny-256")
35
 
36
- color_map = cv2.applyColorMap(np.arange(256, dtype=np.uint8), cv2.COLORMAP_INFERNO)
37
- color_map = torch.from_numpy(color_map).to(device)
38
-
39
  def preprocess_image(image):
40
  image = cv2.resize(image, (128, 72))
41
  image = torch.from_numpy(image).permute(2, 0, 1).unsqueeze(0).float().to(device)
@@ -46,15 +58,13 @@ def plot_depth_map(depth_map, original_image):
46
  ax = fig.add_subplot(111, projection='3d')
47
  x, y = np.meshgrid(range(depth_map.shape[1]), range(depth_map.shape[0]))
48
 
49
- # Resize original image to match depth map dimensions
50
  original_image_resized = cv2.resize(original_image, (depth_map.shape[1], depth_map.shape[0]))
51
  colors = original_image_resized.reshape(depth_map.shape[0], depth_map.shape[1], 3) / 255.0
52
 
53
  ax.plot_surface(x, y, depth_map, facecolors=colors, shade=False)
54
  ax.set_zlim(0, 1)
55
 
56
- # Adjust the view to look down at an angle from a higher position
57
- ax.view_init(elev=45, azim=180) # 180-degree rotation and a higher angle
58
  plt.axis('off')
59
  plt.close(fig)
60
 
@@ -69,14 +79,11 @@ def process_frame(image):
69
  if image is None:
70
  return None
71
  preprocessed = preprocess_image(image)
72
- predicted_depth = model(preprocessed).predicted_depth
73
- depth_map = predicted_depth.squeeze().cpu().numpy()
74
 
75
- # Normalize depth map
76
- depth_map = (depth_map - depth_map.min()) / (depth_map.max() - depth_map.min())
77
 
78
- # Convert BGR to RGB if necessary
79
- if image.shape[2] == 3: # Check if it's a color image
80
  image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
81
 
82
  return plot_depth_map(depth_map, image)
 
1
  import cv2
2
  import torch
3
  import numpy as np
4
+ from transformers import DPTImageProcessor
5
  import gradio as gr
 
6
  import matplotlib.pyplot as plt
7
  from mpl_toolkits.mplot3d import Axes3D
8
 
9
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
 
11
+ # Load your custom trained model
12
+ class CompressedStudentModel(nn.Module):
13
+ def __init__(self):
14
+ super(CompressedStudentModel, self).__init__()
15
+ self.encoder = nn.Sequential(
16
+ nn.Conv2d(3, 64, kernel_size=3, padding=1),
17
+ nn.ReLU(),
18
+ nn.Conv2d(64, 64, kernel_size=3, padding=1),
19
+ nn.ReLU(),
20
+ nn.MaxPool2d(2),
21
+ nn.Conv2d(64, 128, kernel_size=3, padding=1),
22
+ nn.ReLU(),
23
+ nn.Conv2d(128, 128, kernel_size=3, padding=1),
24
+ nn.ReLU(),
25
+ nn.MaxPool2d(2),
26
+ nn.Conv2d(128, 256, kernel_size=3, padding=1),
27
+ nn.ReLU(),
28
+ nn.Conv2d(256, 256, kernel_size=3, padding=1),
29
+ nn.ReLU(),
30
+ )
31
+ self.decoder = nn.Sequential(
32
+ nn.ConvTranspose2d(256, 128, kernel_size=3, stride=2, padding=1, output_padding=1),
33
+ nn.ReLU(),
34
+ nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, output_padding=1),
35
+ nn.ReLU(),
36
+ nn.Conv2d(64, 1, kernel_size=3, padding=1),
37
+ )
38
 
39
+ def forward(self, x):
40
+ features = self.encoder(x)
41
+ depth = self.decoder(features)
42
+ return depth
43
 
44
+ # Initialize and load weights into the student model
45
+ model = CompressedStudentModel().to(device)
46
+ model.load_state_dict(torch.load("huntrezz_depth_v2.pt", map_location=device))
47
+ model.eval()
 
48
 
49
  processor = DPTImageProcessor.from_pretrained("Intel/dpt-swinv2-tiny-256")
50
 
 
 
 
51
  def preprocess_image(image):
52
  image = cv2.resize(image, (128, 72))
53
  image = torch.from_numpy(image).permute(2, 0, 1).unsqueeze(0).float().to(device)
 
58
  ax = fig.add_subplot(111, projection='3d')
59
  x, y = np.meshgrid(range(depth_map.shape[1]), range(depth_map.shape[0]))
60
 
 
61
  original_image_resized = cv2.resize(original_image, (depth_map.shape[1], depth_map.shape[0]))
62
  colors = original_image_resized.reshape(depth_map.shape[0], depth_map.shape[1], 3) / 255.0
63
 
64
  ax.plot_surface(x, y, depth_map, facecolors=colors, shade=False)
65
  ax.set_zlim(0, 1)
66
 
67
+ ax.view_init(elev=45, azim=180)
 
68
  plt.axis('off')
69
  plt.close(fig)
70
 
 
79
  if image is None:
80
  return None
81
  preprocessed = preprocess_image(image)
82
+ predicted_depth = model(preprocessed).squeeze().cpu().numpy()
 
83
 
84
+ depth_map = (predicted_depth - predicted_depth.min()) / (predicted_depth.max() - predicted_depth.min())
 
85
 
86
+ if image.shape[2] == 3:
 
87
  image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
88
 
89
  return plot_depth_map(depth_map, image)