Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

inverse_render.py 5.1 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
  1. import argparse
  2. import math
  3. import os
  4. from torchvision.utils import save_image
  5. import torch
  6. import numpy as np
  7. from PIL import Image
  8. from tqdm import tqdm
  9. import numpy as np
  10. import skvideo.io
  11. import curriculums
  12. from torchvision import transforms
  13. def tensor_to_PIL(img):
  14. img = img.squeeze() * 0.5 + 0.5
  15. return Image.fromarray(img.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy())
  16. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument('generator_path', type=str)
  19. parser.add_argument('image_path', type=str)
  20. parser.add_argument('--seed', type=int, default=None)
  21. parser.add_argument('--image_size', type=int, default=128)
  22. parser.add_argument('--num_frames', type=int, default=64)
  23. parser.add_argument('--max_batch_size', type=int, default=2400000)
  24. opt = parser.parse_args()
  25. generator = torch.load(opt.generator_path, map_location=torch.device(device))
  26. ema_file = opt.generator_path.split('generator')[0] + 'ema.pth'
  27. ema = torch.load(ema_file, map_location=device)
  28. ema.copy_to(generator.parameters())
  29. generator.set_device(device)
  30. generator.eval()
  31. if opt.seed is not None:
  32. torch.manual_seed(opt.seed)
  33. gt_image = Image.open(opt.image_path).convert('RGB')
  34. transform = transforms.Compose(
  35. [transforms.Resize(256), transforms.CenterCrop(256), transforms.Resize((opt.image_size, opt.image_size), interpolation=0), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])
  36. gt_image = transform(gt_image).to(device)
  37. options = {
  38. 'img_size': opt.image_size,
  39. 'fov': 12,
  40. 'ray_start': 0.88,
  41. 'ray_end': 1.12,
  42. 'num_steps': 24,
  43. 'h_stddev': 0,
  44. 'v_stddev': 0,
  45. 'h_mean': torch.tensor(math.pi/2).to(device),
  46. 'v_mean': torch.tensor(math.pi/2).to(device),
  47. 'hierarchical_sample': False,
  48. 'sample_dist': None,
  49. 'clamp_mode': 'relu',
  50. 'nerf_noise': 0,
  51. }
  52. render_options = {
  53. 'img_size': 256,
  54. 'fov': 12,
  55. 'ray_start': 0.88,
  56. 'ray_end': 1.12,
  57. 'num_steps': 48,
  58. 'h_stddev': 0,
  59. 'v_stddev': 0,
  60. 'v_mean': math.pi/2,
  61. 'hierarchical_sample': True,
  62. 'sample_dist': None,
  63. 'clamp_mode': 'relu',
  64. 'nerf_noise': 0,
  65. 'last_back': True,
  66. }
  67. z = torch.randn((10000, 256), device=device)
  68. with torch.no_grad():
  69. frequencies, phase_shifts = generator.siren.mapping_network(z)
  70. w_frequencies = frequencies.mean(0, keepdim=True)
  71. w_phase_shifts = phase_shifts.mean(0, keepdim=True)
  72. w_frequency_offsets = torch.zeros_like(w_frequencies)
  73. w_phase_shift_offsets = torch.zeros_like(w_phase_shifts)
  74. w_frequency_offsets.requires_grad_()
  75. w_phase_shift_offsets.requires_grad_()
  76. frames = []
  77. n_iterations_pose = 0
  78. n_iterations = 700
  79. os.makedirs('debug', exist_ok=True)
  80. save_image(gt_image, "debug/gt.jpg", normalize=True)
  81. optimizer = torch.optim.Adam([w_frequency_offsets, w_phase_shift_offsets], lr=1e-2, weight_decay = 1e-4)
  82. scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 100, gamma=0.75)
  83. for i in range(n_iterations):
  84. noise_w_frequencies = 0.03 * torch.randn_like(w_frequencies) * (n_iterations - i)/n_iterations
  85. noise_w_phase_shifts = 0.03 * torch.randn_like(w_phase_shifts) * (n_iterations - i)/n_iterations
  86. frame, _ = generator.forward_with_frequencies(w_frequencies + noise_w_frequencies + w_frequency_offsets, w_phase_shifts + noise_w_phase_shifts + w_phase_shift_offsets, **options)
  87. loss = torch.nn.MSELoss()(frame, gt_image)
  88. loss = loss.mean()
  89. loss.backward()
  90. optimizer.step()
  91. optimizer.zero_grad()
  92. scheduler.step()
  93. if i % 100 == 0:
  94. save_image(frame, f"debug/{i}.jpg", normalize=True)
  95. with torch.no_grad():
  96. for angle in [-0.7, -0.5, -0.3, 0, 0.3, 0.5, 0.7]:
  97. img, _ = generator.staged_forward_with_frequencies(w_frequencies + w_frequency_offsets, w_phase_shifts + w_phase_shift_offsets, h_mean=(math.pi/2 + angle), max_batch_size=opt.max_batch_size, lock_view_dependence=True, **render_options)
  98. save_image(img, f"debug/{i}_{angle}.jpg", normalize=True)
  99. trajectory = []
  100. for t in np.linspace(0, 1, 24):
  101. pitch = 0.2 * t
  102. yaw = 0
  103. trajectory.append((pitch, yaw))
  104. for t in np.linspace(0, 1, opt.num_frames):
  105. pitch = 0.2 * np.cos(t * 2 * math.pi)
  106. yaw = 0.4 * np.sin(t * 2 * math.pi)
  107. trajectory.append((pitch, yaw))
  108. output_name = 'reconstructed.mp4'
  109. writer = skvideo.io.FFmpegWriter(os.path.join('debug', output_name), outputdict={'-pix_fmt': 'yuv420p', '-crf': '21'})
  110. frames = []
  111. depths = []
  112. with torch.no_grad():
  113. for pitch, yaw in tqdm(trajectory):
  114. render_options['h_mean'] = yaw + 3.14/2
  115. render_options['v_mean'] = pitch + 3.14/2
  116. frame, depth_map = generator.staged_forward_with_frequencies(w_frequencies + w_frequency_offsets, w_phase_shifts + w_phase_shift_offsets, max_batch_size=opt.max_batch_size, lock_view_dependence=True, **render_options)
  117. frames.append(tensor_to_PIL(frame))
  118. depths.append(depth_map.unsqueeze(0).expand(-1, 3, -1, -1).squeeze().permute(1, 2, 0).cpu().numpy())
  119. for frame in frames:
  120. writer.writeFrame(np.array(frame))
  121. writer.close()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...