freealise commited on
Commit
2270054
·
verified ·
1 Parent(s): b595a57

Upload app.txt

Browse files
Files changed (1) hide show
  1. app.txt +1421 -0
app.txt ADDED
@@ -0,0 +1,1421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ from PIL import Image
4
+ import numpy as np
5
+ import os
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from torchvision import transforms
9
+ from torchvision.transforms import Compose
10
+ import tempfile
11
+ from functools import partial
12
+ import spaces
13
+ from zipfile import ZipFile
14
+ from vincenty import vincenty
15
+ import json
16
+ from collections import Counter
17
+ import mediapy
18
+
19
+ #from depth_anything.dpt import DepthAnything
20
+ #from depth_anything.util.transform import Resize, NormalizeImage, PrepareForNet
21
+ from huggingface_hub import hf_hub_download
22
+ from depth_anything_v2.dpt import DepthAnythingV2
23
+
24
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
25
+ model_configs = {
26
+ 'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]},
27
+ 'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]},
28
+ 'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
29
+ 'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]}
30
+ }
31
+ encoder2name = {
32
+ 'vits': 'Small',
33
+ 'vitb': 'Base',
34
+ 'vitl': 'Large',
35
+ 'vitg': 'Giant', # we are undergoing company review procedures to release our giant model checkpoint
36
+ }
37
+
38
+ blurin = "1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
39
+ edge = []
40
+ gradient = None
41
+ params = { "fnum":0 }
42
+ pcolors = []
43
+ frame_selected = 0
44
+ frames = []
45
+ backups = []
46
+ depths = []
47
+ masks = []
48
+ locations = []
49
+ mesh = []
50
+ mesh_n = []
51
+ scene = None
52
+
53
+ def zip_files(files_in, files_out):
54
+ with ZipFile("depth_result.zip", "w") as zipObj:
55
+ for idx, file in enumerate(files_in):
56
+ zipObj.write(file, file.split("/")[-1])
57
+ for idx, file in enumerate(files_out):
58
+ zipObj.write(file, file.split("/")[-1])
59
+ return "depth_result.zip"
60
+
61
+ def create_video(frames, fps, type):
62
+ print("building video result")
63
+ imgs = []
64
+ for j, img in enumerate(frames):
65
+ imgs.append(cv2.cvtColor(cv2.imread(img).astype(np.uint8), cv2.COLOR_BGR2RGB))
66
+
67
+ mediapy.write_video(type + "_result.mp4", imgs, fps=fps)
68
+ return type + "_result.mp4"
69
+
70
+ @torch.no_grad()
71
+ #@spaces.GPU
72
+ def predict_depth(image, model):
73
+ return model.infer_image(image)
74
+
75
+ #def predict_depth(model, image):
76
+ # return model(image)["depth"]
77
+
78
+ def make_video(video_path, outdir='./vis_video_depth', encoder='vits', blur_data=blurin, o=1, b=32):
79
+ if encoder not in ["vitl","vitb","vits","vitg"]:
80
+ encoder = "vits"
81
+
82
+ model_name = encoder2name[encoder]
83
+ model = DepthAnythingV2(**model_configs[encoder])
84
+ filepath = hf_hub_download(repo_id=f"depth-anything/Depth-Anything-V2-{model_name}", filename=f"depth_anything_v2_{encoder}.pth", repo_type="model")
85
+ state_dict = torch.load(filepath, map_location="cpu")
86
+ model.load_state_dict(state_dict)
87
+ model = model.to(DEVICE).eval()
88
+
89
+ #mapper = {"vits":"small","vitb":"base","vitl":"large"}
90
+ # DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
91
+ # model = DepthAnything.from_pretrained('LiheYoung/depth_anything_vitl14').to(DEVICE).eval()
92
+ # Define path for temporary processed frames
93
+ #temp_frame_dir = tempfile.mkdtemp()
94
+
95
+ #margin_width = 50
96
+ #to_tensor_transform = transforms.ToTensor()
97
+
98
+ #DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
99
+ # depth_anything = DepthAnything.from_pretrained('LiheYoung/depth_anything_{}14'.format(encoder)).to(DEVICE).eval()
100
+ #depth_anything = pipeline(task = "depth-estimation", model=f"nielsr/depth-anything-{mapper[encoder]}")
101
+
102
+ # total_params = sum(param.numel() for param in depth_anything.parameters())
103
+ # print('Total parameters: {:.2f}M'.format(total_params / 1e6))
104
+
105
+ #transform = Compose([
106
+ # Resize(
107
+ # width=518,
108
+ # height=518,
109
+ # resize_target=False,
110
+ # keep_aspect_ratio=True,
111
+ # ensure_multiple_of=14,
112
+ # resize_method='lower_bound',
113
+ # image_interpolation_method=cv2.INTER_CUBIC,
114
+ # ),
115
+ # NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
116
+ # PrepareForNet(),
117
+ #])
118
+
119
+ if os.path.isfile(video_path):
120
+ if video_path.endswith('txt'):
121
+ with open(video_path, 'r') as f:
122
+ lines = f.read().splitlines()
123
+ else:
124
+ filenames = [video_path]
125
+ else:
126
+ filenames = os.listdir(video_path)
127
+ filenames = [os.path.join(video_path, filename) for filename in filenames if not filename.startswith('.')]
128
+ filenames.sort()
129
+
130
+ # os.makedirs(outdir, exist_ok=True)
131
+ global masks
132
+
133
+ for k, filename in enumerate(filenames):
134
+ file_size = os.path.getsize(filename)/1024/1024
135
+ if file_size > 128.0:
136
+ print(f'File size of {filename} larger than 128Mb, sorry!')
137
+ return filename
138
+ print('Progress {:}/{:},'.format(k+1, len(filenames)), 'Processing', filename)
139
+
140
+ raw_video = cv2.VideoCapture(filename)
141
+ frame_width, frame_height = int(raw_video.get(cv2.CAP_PROP_FRAME_WIDTH)), int(raw_video.get(cv2.CAP_PROP_FRAME_HEIGHT))
142
+ frame_rate = int(raw_video.get(cv2.CAP_PROP_FPS))
143
+ if frame_rate < 1:
144
+ frame_rate = 1
145
+ cframes = int(raw_video.get(cv2.CAP_PROP_FRAME_COUNT))
146
+ print(f'frames: {cframes}, fps: {frame_rate}')
147
+ # output_width = frame_width * 2 + margin_width
148
+
149
+ #filename = os.path.basename(filename)
150
+ # output_path = os.path.join(outdir, filename[:filename.rfind('.')] + '_video_depth.mp4')
151
+ #with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmpfile:
152
+ # output_path = tmpfile.name
153
+ #out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"avc1"), frame_rate, (output_width, frame_height))
154
+ #fourcc = cv2.VideoWriter_fourcc(*'mp4v')
155
+ #out = cv2.VideoWriter(output_path, fourcc, frame_rate, (output_width, frame_height))
156
+
157
+ count = 0
158
+ n = 0
159
+ depth_frames = []
160
+ orig_frames = []
161
+ backup_frames = []
162
+ thumbnail_old = []
163
+
164
+ while raw_video.isOpened():
165
+ ret, raw_frame = raw_video.read()
166
+ if not ret:
167
+ break
168
+ else:
169
+ print(count)
170
+
171
+ frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2RGB) / 255.0
172
+ frame_pil = Image.fromarray((frame * 255).astype(np.uint8))
173
+ #frame = transform({'image': frame})['image']
174
+ #frame = torch.from_numpy(frame).unsqueeze(0).to(DEVICE)
175
+ #raw_frame_bg = cv2.medianBlur(raw_frame, 255)
176
+
177
+ #
178
+ depth = predict_depth(raw_frame[:, :, ::-1], model)
179
+ depth_gray = ((depth - depth.min()) / (depth.max() - depth.min()) * 255.0).astype(np.uint8)
180
+ #
181
+
182
+ #depth = to_tensor_transform(predict_depth(depth_anything, frame_pil))
183
+ #depth = F.interpolate(depth[None], (frame_height, frame_width), mode='bilinear', align_corners=False)[0, 0]
184
+ #depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255.0
185
+ #depth = depth.cpu().numpy().astype(np.uint8)
186
+ #depth_color = cv2.applyColorMap(depth, cv2.COLORMAP_BONE)
187
+ #depth_gray = cv2.cvtColor(depth_color, cv2.COLOR_RGBA2GRAY)
188
+
189
+ # Remove white border around map:
190
+ # define lower and upper limits of white
191
+ #white_lo = np.array([250,250,250])
192
+ #white_hi = np.array([255,255,255])
193
+ # mask image to only select white
194
+ mask = cv2.inRange(depth_gray[0:int(depth_gray.shape[0]/8*7)-1, 0:depth_gray.shape[1]], 250, 255)
195
+ # change image to black where we found white
196
+ depth_gray[0:int(depth_gray.shape[0]/8*7)-1, 0:depth_gray.shape[1]][mask>0] = 0
197
+
198
+ mask = cv2.inRange(depth_gray[int(depth_gray.shape[0]/8*7):depth_gray.shape[0], 0:depth_gray.shape[1]], 192, 255)
199
+ depth_gray[int(depth_gray.shape[0]/8*7):depth_gray.shape[0], 0:depth_gray.shape[1]][mask>0] = 192
200
+
201
+ depth_color = cv2.cvtColor(depth_gray, cv2.COLOR_GRAY2BGR)
202
+ # split_region = np.ones((frame_height, margin_width, 3), dtype=np.uint8) * 255
203
+ # combined_frame = cv2.hconcat([raw_frame, split_region, depth_color])
204
+
205
+ # out.write(combined_frame)
206
+ # frame_path = os.path.join(temp_frame_dir, f"frame_{count:05d}.png")
207
+ # cv2.imwrite(frame_path, combined_frame)
208
+
209
+ #raw_frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2BGRA)
210
+ #raw_frame[:, :, 3] = 255
211
+
212
+ if cframes < 16:
213
+ thumbnail = cv2.cvtColor(cv2.resize(raw_frame, (16,32)), cv2.COLOR_BGR2GRAY).flatten()
214
+ if len(thumbnail_old) > 0:
215
+ diff = thumbnail - thumbnail_old
216
+ #print(diff)
217
+ c = Counter(diff)
218
+ value, cc = c.most_common()[0]
219
+ if value == 0 and cc > int(16*32*0.8):
220
+ count += 1
221
+ continue
222
+ thumbnail_old = thumbnail
223
+
224
+ blur_frame = blur_image(raw_frame, depth_color, blur_data)
225
+
226
+ # encoding depth within original video
227
+ blur_frame = (int(blur_frame / 17) * 17).astype(np.uint8)
228
+ depth_r = int(depth_gray / 17).astype(np.uint8)
229
+ # may use green channel for 16 levels of opacity
230
+ depth_b = depth_gray - depth_r * 17
231
+ blur_frame[:,:,0] = blur_frame[:,:,0] + depth_r
232
+ # blur_frame[:,:,1] = blur_frame[:,:,1] + opacity_g
233
+ blur_frame[:,:,2] = blur_frame[:,:,2] + depth_b
234
+
235
+ cv2.imwrite(f"f{count}.jpg", blur_frame)
236
+ orig_frames.append(f"f{count}.jpg")
237
+
238
+ cv2.imwrite(f"f{count}_.jpg", blur_frame)
239
+ backup_frames.append(f"f{count}_.jpg")
240
+
241
+ cv2.imwrite(f"f{count}_dmap.jpg", depth_color)
242
+ depth_frames.append(f"f{count}_dmap.jpg")
243
+
244
+ depth_gray = seg_frame(depth_gray, o, b) + 128
245
+ #print(depth_gray[depth_gray>128]-128)
246
+
247
+ cv2.imwrite(f"f{count}_mask.jpg", depth_gray)
248
+ masks.append(f"f{count}_mask.jpg")
249
+ count += 1
250
+
251
+ final_vid = create_video(orig_frames, frame_rate, "orig")
252
+ depth_vid = create_video(depth_frames, frame_rate, "depth")
253
+
254
+ final_zip = zip_files(orig_frames, depth_frames)
255
+ raw_video.release()
256
+ # out.release()
257
+ cv2.destroyAllWindows()
258
+
259
+ global gradient
260
+ global frame_selected
261
+ global depths
262
+ global frames
263
+ global backups
264
+ frames = orig_frames
265
+ backups = backup_frames
266
+ depths = depth_frames
267
+
268
+ if depth_color.shape[0] == 2048: #height
269
+ gradient = cv2.imread('./gradient_large.png').astype(np.uint8)
270
+ elif depth_color.shape[0] == 1024:
271
+ gradient = cv2.imread('./gradient.png').astype(np.uint8)
272
+ else:
273
+ gradient = cv2.imread('./gradient_small.png').astype(np.uint8)
274
+
275
+ return final_vid, final_zip, frames, masks[frame_selected], depths, depth_vid #output_path
276
+
277
+ def depth_edges_mask(depth):
278
+ """Returns a mask of edges in the depth map.
279
+ Args:
280
+ depth: 2D numpy array of shape (H, W) with dtype float32.
281
+ Returns:
282
+ mask: 2D numpy array of shape (H, W) with dtype bool.
283
+ """
284
+ # Compute the x and y gradients of the depth map.
285
+ depth_dx, depth_dy = np.gradient(depth)
286
+ # Compute the gradient magnitude.
287
+ depth_grad = np.sqrt(depth_dx ** 2 + depth_dy ** 2)
288
+ # Compute the edge mask.
289
+ mask = depth_grad > 0.05
290
+ return mask
291
+
292
+ def pano_depth_to_world_points(depth):
293
+ """
294
+ 360 depth to world points
295
+ given 2D depth is an equirectangular projection of a spherical image
296
+ Treat depth as radius
297
+ longitude : -pi to pi
298
+ latitude : -pi/2 to pi/2
299
+ """
300
+
301
+ # Convert depth to radius
302
+ radius = (255 - depth.flatten())
303
+
304
+ lon = np.linspace(0, np.pi*2, depth.shape[1])
305
+ lat = np.linspace(0, np.pi, depth.shape[0])
306
+ lon, lat = np.meshgrid(lon, lat)
307
+ lon = lon.flatten()
308
+ lat = lat.flatten()
309
+
310
+ pts3d = [[0,0,0]]
311
+ uv = [[0,0]]
312
+ nl = [[0,0,0]]
313
+ for i in range(0, 1): #(0,2)
314
+ for j in range(0, 1): #(0,2)
315
+ #rnd_lon = (np.random.rand(depth.shape[0]*depth.shape[1]) - 0.5) / 8
316
+ #rnd_lat = (np.random.rand(depth.shape[0]*depth.shape[1]) - 0.5) / 8
317
+ d_lon = lon + i/2 * np.pi*2 / depth.shape[1]
318
+ d_lat = lat + j/2 * np.pi / depth.shape[0]
319
+
320
+ nx = np.cos(d_lon) * np.sin(d_lat)
321
+ ny = np.cos(d_lat)
322
+ nz = np.sin(d_lon) * np.sin(d_lat)
323
+
324
+ # Convert to cartesian coordinates
325
+ x = radius * nx
326
+ y = radius * ny
327
+ z = radius * nz
328
+
329
+ pts = np.stack([x, y, z], axis=1)
330
+ uvs = np.stack([lon/np.pi/2, lat/np.pi], axis=1)
331
+ nls = np.stack([-nx, -ny, -nz], axis=1)
332
+
333
+ pts3d = np.concatenate((pts3d, pts), axis=0)
334
+ uv = np.concatenate((uv, uvs), axis=0)
335
+ nl = np.concatenate((nl, nls), axis=0)
336
+ #print(f'i: {i}, j: {j}')
337
+ j = j+1
338
+ i = i+1
339
+
340
+ return [pts3d, uv, nl]
341
+
342
+ def rgb2gray(rgb):
343
+ return np.dot(rgb[...,:3], [0.333, 0.333, 0.333])
344
+
345
+ def get_mesh(image, depth, blur_data, loadall):
346
+ global depths
347
+ global pcolors
348
+ global frame_selected
349
+ global mesh
350
+ global mesh_n
351
+ global scene
352
+ if loadall == False:
353
+ mesh = []
354
+ mesh_n = []
355
+ fnum = frame_selected
356
+
357
+ #print(image[fnum][0])
358
+ #print(depth["composite"])
359
+
360
+ depthc = cv2.imread(depths[frame_selected], cv2.IMREAD_UNCHANGED).astype(np.uint8)
361
+ blur_img = blur_image(cv2.imread(image[fnum][0], cv2.IMREAD_UNCHANGED).astype(np.uint8), depthc, blur_data)
362
+ gdepth = cv2.cvtColor(depthc, cv2.COLOR_RGB2GRAY) #rgb2gray(depthc)
363
+
364
+ print('depth to gray - ok')
365
+ points = pano_depth_to_world_points(gdepth)
366
+ pts3d = points[0]
367
+ uv = points[1]
368
+ nl = points[2]
369
+ print('radius from depth - ok')
370
+
371
+ # Create a trimesh mesh from the points
372
+ # Each pixel is connected to its 4 neighbors
373
+ # colors are the RGB values of the image
374
+ uvs = uv.reshape(-1, 2)
375
+ #print(uvs)
376
+ #verts = pts3d.reshape(-1, 3)
377
+ verts = [[0,0,0]]
378
+ normals = nl.reshape(-1, 3)
379
+ rgba = cv2.cvtColor(blur_img, cv2.COLOR_RGB2RGBA)
380
+ colors = rgba.reshape(-1, 4)
381
+ clrs = [[128,128,128,0]]
382
+
383
+ #for i in range(0,1): #(0,4)
384
+ #clrs = np.concatenate((clrs, colors), axis=0)
385
+ #i = i+1
386
+ #verts, clrs
387
+
388
+ #pcd = o3d.geometry.TriangleMesh.create_tetrahedron()
389
+ #pcd.compute_vertex_normals()
390
+ #pcd.paint_uniform_color((1.0, 1.0, 1.0))
391
+ #mesh.append(pcd)
392
+ #print(mesh[len(mesh)-1])
393
+ if not str(fnum) in mesh_n:
394
+ mesh_n.append(str(fnum))
395
+ print('mesh - ok')
396
+
397
+ # Save as glb
398
+ #glb_file = tempfile.NamedTemporaryFile(suffix='.glb', delete=False)
399
+ #o3d.io.write_triangle_mesh(glb_file.name, pcd)
400
+ #print('file - ok')
401
+ return "./TriangleWithoutIndices.gltf", ",".join(mesh_n)
402
+
403
+
404
+ def blur_image(image, depth, blur_data):
405
+ blur_a = blur_data.split()
406
+ #print(f'blur data {blur_data}')
407
+
408
+ blur_frame = image.copy()
409
+ j = 0
410
+ while j < 256:
411
+ i = 255 - j
412
+ blur_lo = np.array([i,i,i])
413
+ blur_hi = np.array([i+1,i+1,i+1])
414
+ blur_mask = cv2.inRange(depth, blur_lo, blur_hi)
415
+
416
+ #print(f'kernel size {int(blur_a[j])}')
417
+ blur = cv2.GaussianBlur(image, (int(blur_a[j]), int(blur_a[j])), 0)
418
+
419
+ blur_frame[blur_mask>0] = blur[blur_mask>0]
420
+ j = j + 1
421
+
422
+ white = cv2.inRange(blur_frame, np.array([255,255,255]), np.array([255,255,255]))
423
+ blur_frame[white>0] = (254,254,254)
424
+
425
+ return blur_frame
426
+
427
+ def loadfile(f):
428
+ return f
429
+
430
+ def show_json(txt):
431
+ data = json.loads(txt)
432
+ print(txt)
433
+ i=0
434
+ while i < len(data[2]):
435
+ data[2][i] = data[2][i]["image"]["path"]
436
+ data[4][i] = data[4][i]["path"]
437
+ i=i+1
438
+ return data[0]["video"]["path"], data[1]["path"], data[2], data[3]["background"]["path"], data[4], data[5]
439
+
440
+
441
+ def seg_frame(newmask, b, d):
442
+
443
+ if newmask.shape[0] == 2048: #height
444
+ gd = cv2.imread('./gradient_large.png', cv2.IMREAD_GRAYSCALE).astype(np.uint8)
445
+ elif newmask.shape[0] == 1024:
446
+ gd = cv2.imread('./gradient.png', cv2.IMREAD_GRAYSCALE).astype(np.uint8)
447
+ else:
448
+ gd = cv2.imread('./gradient_small.png', cv2.IMREAD_GRAYSCALE).astype(np.uint8)
449
+
450
+ newmask[np.absolute(newmask.astype(np.int16)-gd.astype(np.int16))<16] = 0
451
+ ret,newmask = cv2.threshold(newmask,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
452
+
453
+ #b = 1
454
+ #d = 32
455
+ element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * b + 1, 2 * b + 1), (b, b))
456
+ bd = cv2.erode(newmask, element)
457
+ element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * d + 1, 2 * d + 1), (d, d))
458
+ bg = cv2.dilate(newmask, element)
459
+ bg[bg.shape[0]-64:bg.shape[0],0:bg.shape[1]] = 0
460
+
461
+ mask = np.zeros(newmask.shape[:2],np.uint8)
462
+ # https://docs.opencv.org/4.x/d8/d83/tutorial_py_grabcut.html
463
+ # wherever it is marked white (sure foreground), change mask=1
464
+ # wherever it is marked black (sure background), change mask=0
465
+ mask[bg == 255] = 3
466
+ mask[bd == 255] = 1 #2: probable bg, 3: probable fg
467
+
468
+ return mask
469
+
470
+
471
+ def select_frame(d, evt: gr.SelectData):
472
+ global frame_selected
473
+ global depths
474
+ global masks
475
+ global edge
476
+
477
+ if evt.index != frame_selected:
478
+ edge = []
479
+ frame_selected = evt.index
480
+
481
+ return depths[frame_selected], frame_selected
482
+
483
+ def switch_rows(v):
484
+ global frames
485
+ global depths
486
+ if v == True:
487
+ print(depths[0])
488
+ return depths
489
+ else:
490
+ print(frames[0])
491
+ return frames
492
+
493
+
494
+ def bincount(a):
495
+ a2D = a.reshape(-1,a.shape[-1])
496
+ col_range = (256, 256, 256) # generically : a2D.max(0)+1
497
+ a1D = np.ravel_multi_index(a2D.T, col_range)
498
+ return list(reversed(np.unravel_index(np.bincount(a1D).argmax(), col_range)))
499
+
500
+ def reset_mask(d):
501
+ global frame_selected
502
+ global frames
503
+ global backups
504
+ global masks
505
+ global depths
506
+ global edge
507
+
508
+ edge = []
509
+ backup = cv2.imread(backups[frame_selected]).astype(np.uint8)
510
+ cv2.imwrite(frames[frame_selected], backup)
511
+
512
+ d["layers"][0][0:d["layers"][0].shape[0], 0:d["layers"][0].shape[1]] = (0,0,0,0)
513
+
514
+ return gr.ImageEditor(value=d)
515
+
516
+
517
+ def draw_mask(o, b, v, d, evt: gr.EventData):
518
+ global frames
519
+ global depths
520
+ global params
521
+ global frame_selected
522
+ global masks
523
+ global gradient
524
+ global edge
525
+
526
+ points = json.loads(v)
527
+ pts = np.array(points, np.int32)
528
+ pts = pts.reshape((-1,1,2))
529
+
530
+ if len(edge) == 0 or params["fnum"] != frame_selected:
531
+ if params["fnum"] != frame_selected:
532
+ d["background"] = cv2.imread(depths[frame_selected]).astype(np.uint8)
533
+ params["fnum"] = frame_selected
534
+
535
+ bg = cv2.cvtColor(d["background"], cv2.COLOR_RGBA2GRAY)
536
+ bg[bg==255] = 0
537
+
538
+ edge = bg.copy()
539
+ else:
540
+ bg = edge.copy()
541
+
542
+ x = points[len(points)-1][0]
543
+ y = points[len(points)-1][1]
544
+
545
+ mask = cv2.imread(masks[frame_selected], cv2.IMREAD_GRAYSCALE).astype(np.uint8)
546
+ mask[mask==128] = 0
547
+ print(mask[mask>0]-128)
548
+ d["layers"][0] = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGBA)
549
+
550
+ sel = cv2.floodFill(mask, None, (x, y), 1, 2, 2, (4 | cv2.FLOODFILL_FIXED_RANGE))[2] #(4 | cv2.FLOODFILL_FIXED_RANGE | cv2.FLOODFILL_MASK_ONLY | 255 << 8)
551
+ # 255 << 8 tells to fill with the value 255)
552
+ sel = sel[1:sel.shape[0]-1, 1:sel.shape[1]-1]
553
+
554
+ d["layers"][0][sel==0] = (0,0,0,0)
555
+
556
+
557
+ mask = cv2.cvtColor(d["layers"][0], cv2.COLOR_RGBA2GRAY)
558
+ mask[mask==0] = 128
559
+ print(mask[mask>128]-128)
560
+ mask, bgdModel, fgdModel = cv2.grabCut(cv2.cvtColor(d["background"], cv2.COLOR_RGBA2RGB), mask-128, None,None,None,15, cv2.GC_INIT_WITH_MASK)
561
+ mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
562
+
563
+ frame = cv2.imread(frames[frame_selected], cv2.IMREAD_UNCHANGED).astype(np.uint8)
564
+ frame[mask>0] = (255,255,255)
565
+ cv2.imwrite(frames[frame_selected], frame)
566
+
567
+ switch_rows(False)
568
+ return gr.ImageEditor(value=d)
569
+
570
+
571
+ load_model="""
572
+ async(c, o, p, d, n, m, s)=>{
573
+ var intv = setInterval(function(){
574
+ if (document.getElementById("model3D").getElementsByTagName("canvas")[0]) {
575
+ try {
576
+ if (typeof BABYLON !== "undefined" && BABYLON.Engine && BABYLON.Engine.LastCreatedScene) {
577
+ BABYLON.Engine.LastCreatedScene.onAfterRenderObservable.add(function() { //onDataLoadedObservable
578
+
579
+ var then = new Date().getTime();
580
+ var now, delta;
581
+ const interval = 1000 / 25;
582
+ const tolerance = 0.1;
583
+
584
+ BABYLON.Engine.LastCreatedScene.getEngine().stopRenderLoop();
585
+ BABYLON.Engine.LastCreatedScene.getEngine().runRenderLoop(function () {
586
+ now = new Date().getTime();
587
+ delta = now - then;
588
+ then = now - (delta % interval);
589
+ if (delta >= interval - tolerance) {
590
+ BABYLON.Engine.LastCreatedScene.render();
591
+ }
592
+ });
593
+
594
+ BABYLON.Engine.LastCreatedScene.getEngine().setHardwareScalingLevel(1.0);
595
+ BABYLON.Engine.LastCreatedScene.clearColor = new BABYLON.Color4(255,255,255,255);
596
+ BABYLON.Engine.LastCreatedScene.ambientColor = new BABYLON.Color4(255,255,255,255);
597
+ //BABYLON.Engine.LastCreatedScene.autoClear = false;
598
+ //BABYLON.Engine.LastCreatedScene.autoClearDepthAndStencil = false;
599
+ /*for (var i=0; i<BABYLON.Engine.LastCreatedScene.getNodes().length; i++) {
600
+ if (BABYLON.Engine.LastCreatedScene.getNodes()[i].material) {
601
+ BABYLON.Engine.LastCreatedScene.getNodes()[i].material.pointSize = Math.ceil(Math.log2(Math.PI/document.getElementById("zoom").value));
602
+ }
603
+ }*/
604
+ BABYLON.Engine.LastCreatedScene.getAnimationRatio();
605
+ });
606
+
607
+ if (!BABYLON.Engine.LastCreatedScene.activeCamera.metadata) {
608
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata = {
609
+ pipeline: new BABYLON.DefaultRenderingPipeline("default", true, BABYLON.Engine.LastCreatedScene, [BABYLON.Engine.LastCreatedScene.activeCamera])
610
+ }
611
+ }
612
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.samples = 4;
613
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.imageProcessing.contrast = 1.0;
614
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.imageProcessing.exposure = 1.0;
615
+
616
+ //BABYLON.Engine.LastCreatedScene.activeCamera.detachControl(document.getElementById("model3D").getElementsByTagName("canvas")[0]);
617
+ BABYLON.Engine.LastCreatedScene.activeCamera.inertia = 0.0;
618
+ //pan
619
+ BABYLON.Engine.LastCreatedScene.activeCamera.panningInertia = 0.0;
620
+ BABYLON.Engine.LastCreatedScene.activeCamera.panningDistanceLimit = 16;
621
+ BABYLON.Engine.LastCreatedScene.activeCamera.panningSensibility = 16;
622
+ //zoom
623
+ BABYLON.Engine.LastCreatedScene.activeCamera.pinchDeltaPercentage = 1/256;
624
+ BABYLON.Engine.LastCreatedScene.activeCamera.wheelDeltaPercentage = 1/256;
625
+ BABYLON.Engine.LastCreatedScene.activeCamera.upperRadiusLimit = (1.57-0.157)*16;
626
+ BABYLON.Engine.LastCreatedScene.activeCamera.lowerRadiusLimit = 0.0;
627
+ //BABYLON.Engine.LastCreatedScene.activeCamera.attachControl(document.getElementById("model3D").getElementsByTagName("canvas")[0], false);
628
+
629
+ BABYLON.Engine.LastCreatedScene.activeCamera.fov = document.getElementById("zoom").value;
630
+
631
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].style.filter = "blur(" + Math.ceil(Math.log2(Math.PI/document.getElementById("zoom").value))/2.0*Math.sqrt(2.0) + "px)";
632
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].oncontextmenu = function(e){e.preventDefault();}
633
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].ondrag = function(e){e.preventDefault();}
634
+
635
+ document.getElementById("model3D").appendChild(document.getElementById("compass_box"));
636
+ window.coords = JSON.parse(document.getElementById("coords").getElementsByTagName("textarea")[0].value);
637
+ window.counter = 0;
638
+
639
+ if (o.indexOf(""+n) < 0) {
640
+ if (o != "") { o += ","; }
641
+ o += n;
642
+ }
643
+ //alert(o);
644
+ var o_ = o.split(",");
645
+ var q = BABYLON.Engine.LastCreatedScene.meshes;
646
+ for(i = 0; i < q.length; i++) {
647
+ let mesh = q[i];
648
+ mesh.dispose(false, true);
649
+ }
650
+ var dome = [];
651
+ /*for (var j=0; j<o_.length; j++) {
652
+ o_[j] = parseInt(o_[j]);
653
+ dome[j] = new BABYLON.PhotoDome("dome"+j, p[o_[j]].image.url,
654
+ {
655
+ resolution: 16,
656
+ size: 512
657
+ }, BABYLON.Engine.LastCreatedScene);
658
+ var q = BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-2]._children;
659
+ for(i = 0; i < q.length; i++) {
660
+ let mesh = q[i];
661
+ mesh.dispose(false, true);
662
+ }
663
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].name = "dome"+j;
664
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].scaling.z = -1;
665
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].alphaIndex = o_.length-j;
666
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].visibility = 0.9999;
667
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].material.diffuseTexture.hasAlpha = true;
668
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].material.useAlphaFromDiffuseTexture = true;
669
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].applyDisplacementMap(m[o_[j]].url, 0, 255, function(m){try{alert(BABYLON.Engine.Version);}catch(e){alert(e);}}, null, null, true, function(e){alert(e);});
670
+
671
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].rotationQuaternion = null;
672
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].position.z = coords[o_[j]].lat;
673
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].position.x = coords[o_[j]].lng;
674
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].rotation.y = coords[o_[j]].heading / 180 * Math.PI;
675
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].rotation.z = -coords[o_[j]].pitch / 180 * Math.PI;
676
+ }*/
677
+
678
+ if (s == false) {
679
+ v_url = document.getElementById("output_video").getElementsByTagName("video")[0].src;
680
+ } else {
681
+ v_url = document.getElementById("depth_video").getElementsByTagName("video")[0].src;
682
+ }
683
+ window.videoDome = new BABYLON.VideoDome(
684
+ "videoDome", [v_url],
685
+ {
686
+ resolution: 16,
687
+ size: 512,
688
+ clickToPlay: false,
689
+ }, BABYLON.Engine.LastCreatedScene
690
+ );
691
+ var q = BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-2]._children;
692
+ for (i = 0; i < q.length; i++) {
693
+ let mesh = q[i];
694
+ mesh.dispose(false, true);
695
+ }
696
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].rotationQuaternion = null;
697
+ //BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].position.z = coords[counter].lat;
698
+ //BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].position.x = coords[counter].lng;
699
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].rotation.y = coords[counter].heading / 180 * Math.PI;
700
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].rotation.z = -coords[counter].pitch / 180 * Math.PI;
701
+
702
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].scaling.z = -1;
703
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].material.diffuseTexture.hasAlpha = true;
704
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].material.useAlphaFromDiffuseTexture = true;
705
+ //BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].material.emissiveTexture = videoDome.videoTexture;
706
+ //BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].material.emissiveTexture.hasAlpha = true;
707
+ //BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].material.useAlphaFromEmissiveTexture = true;
708
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].alphaIndex = 1;
709
+ BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1].visibility = 0.9999;
710
+
711
+ window.md = false;
712
+ window.rd = false;
713
+ window.compass = document.getElementById("compass");
714
+ window.x = 0;
715
+ window.y = 0;
716
+ window.xold = 0;
717
+ window.yold = 0;
718
+ window.buffer = null;
719
+ window.bufferCanvas = document.createElement("canvas");
720
+ window.ctx = bufferCanvas.getContext("2d", { willReadFrequently: true });
721
+ window.video = document.getElementById("depth_video").getElementsByTagName("video")[0];
722
+ window.parallax = 0;
723
+ window.xdir = new BABYLON.Vector3(1, 0, 0);
724
+ window.rdir = new BABYLON.Vector3(0, 0, 0);
725
+ window.videoDomeMesh = BABYLON.Engine.LastCreatedScene.meshes[BABYLON.Engine.LastCreatedScene.meshes.length-1];
726
+
727
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].addEventListener('pointermove', function(evt) {
728
+ if (md === true) {
729
+ rdir = BABYLON.Engine.LastCreatedScene.activeCamera.getDirection(xdir);
730
+ videoDomeMesh.position.x = parallax * rdir.x;
731
+ videoDomeMesh.position.z = parallax * rdir.z;
732
+
733
+ try {
734
+ compass.style.transform = "rotateX(" + (BABYLON.Engine.LastCreatedScene.activeCamera.beta-Math.PI/2) + "rad) rotateZ(" + BABYLON.Engine.LastCreatedScene.activeCamera.alpha + "rad)";
735
+ } catch(e) {alert(e);}
736
+ }
737
+ if (rd === true) {
738
+ x = parseInt(evt.clientX - evt.target.getBoundingClientRect().x);
739
+ y = parseInt(evt.clientY - evt.target.getBoundingClientRect().y);
740
+
741
+ if (Math.abs(BABYLON.Engine.LastCreatedScene.activeCamera.radius) > (1.57-0.157)*16) {
742
+ BABYLON.Engine.LastCreatedScene.activeCamera.radius = (1.57-0.157)*16;
743
+ } else {
744
+ BABYLON.Engine.LastCreatedScene.activeCamera.fov = BABYLON.Engine.LastCreatedScene.activeCamera.radius/16 + 0.157;
745
+ }
746
+ document.getElementById('zoom').value = BABYLON.Engine.LastCreatedScene.activeCamera.fov;
747
+ document.getElementById('zoom').parentNode.childNodes[2].innerText = document.getElementById('zoom').value;
748
+
749
+ xold=x;
750
+ yold=y;
751
+ }
752
+ });
753
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].addEventListener('pointerdown', function() {
754
+ md = true;
755
+ });
756
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].addEventListener('pointerup', function() {
757
+ md = false;
758
+ rd = false;
759
+ });
760
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].addEventListener('pointercancel', function() {
761
+ md = false;
762
+ rd = false;
763
+ });
764
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].addEventListener('pointerleave', function() {
765
+ md = false;
766
+ rd = false;
767
+ });
768
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].addEventListener('pointerout', function() {
769
+ md = false;
770
+ rd = false;
771
+ });
772
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].addEventListener('contextmenu', function() {
773
+ rd = true;
774
+ });
775
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].addEventListener('gesturestart', function() {
776
+ rd = true;
777
+ });
778
+ document.getElementById("model3D").getElementsByTagName("canvas")[0].addEventListener('gestureend', function() {
779
+ rd = false;
780
+ });
781
+
782
+
783
+ function requestMap() {
784
+ try {
785
+ ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
786
+ videoDome.videoTexture.video.pause();
787
+ video.pause();
788
+ if (buffer) {
789
+ counter = parseInt(video.currentTime);
790
+ if (!coords[counter]) {counter = coords.length-1;}
791
+ applyDisplacementMapFromBuffer(videoDomeMesh, buffer, video.videoWidth, video.videoHeight, 0, -1, null, null, true);
792
+ }
793
+ buffer = ctx.getImageData(0, 0, video.videoWidth, video.videoHeight).data;
794
+ applyDisplacementMapFromBuffer(videoDomeMesh, buffer, video.videoWidth, video.videoHeight, 0, 1, null, null, true);
795
+ } catch(e) {alert(e)}
796
+ }
797
+ window.requestMap = requestMap;
798
+
799
+ videoDome.videoTexture.video.oncanplaythrough = function () {
800
+ document.getElementById('seek').innerHTML = '';
801
+ for (var i=0; i<videoDome.videoTexture.video.duration; i++) {
802
+ document.getElementById('seek').innerHTML += '<a href="#" style="position:absolute;left:'+(56+coords[i].lng/2)+'px;top:'+(56-coords[i].lat/2)+'px;" onclick="seek('+i+');">-'+i+'-</a> ';
803
+ }
804
+ bufferCanvas.width = video.videoWidth;
805
+ bufferCanvas.height = video.videoHeight;
806
+
807
+ videoPlay();
808
+ };
809
+
810
+ //var debugLayer = BABYLON.Engine.LastCreatedScene.debugLayer.show();
811
+
812
+ if (document.getElementById("model")) {
813
+ document.getElementById("model").appendChild(document.getElementById("model3D"));
814
+ toggleDisplay("model");
815
+ }
816
+
817
+ clearInterval(intv);
818
+ }
819
+ } catch(e) {alert(e);}
820
+ }
821
+ }, 40);
822
+ }
823
+ """
824
+
825
+ js = """
826
+ async()=>{
827
+ console.log('Hi');
828
+
829
+ const chart = document.getElementById('chart');
830
+ const blur_in = document.getElementById('blur_in').getElementsByTagName('textarea')[0];
831
+ var md = false;
832
+ var xold = 128;
833
+ var yold = 32;
834
+ var a = new Array(256);
835
+ var l;
836
+
837
+ for (var i=0; i<256; i++) {
838
+ const hr = document.createElement('hr');
839
+ hr.style.backgroundColor = 'hsl(0,0%,' + (100-i/256*100) + '%)';
840
+ chart.appendChild(hr);
841
+ }
842
+
843
+ function resetLine() {
844
+ a.fill(1);
845
+ for (var i=0; i<256; i++) {
846
+ chart.childNodes[i].style.height = a[i] + 'px';
847
+ chart.childNodes[i].style.marginTop = '32px';
848
+ }
849
+ }
850
+ resetLine();
851
+ window.resetLine = resetLine;
852
+
853
+ function pointerDown(x, y) {
854
+ md = true;
855
+ xold = parseInt(x - chart.getBoundingClientRect().x);
856
+ yold = parseInt(y - chart.getBoundingClientRect().y);
857
+ chart.title = xold + ',' + yold;
858
+ }
859
+ window.pointerDown = pointerDown;
860
+
861
+ function pointerUp() {
862
+ md = false;
863
+ var evt = document.createEvent('Event');
864
+ evt.initEvent('input', true, false);
865
+ blur_in.dispatchEvent(evt);
866
+ chart.title = '';
867
+ }
868
+ window.pointerUp = pointerUp;
869
+
870
+ function lerp(y1, y2, mu) { return y1*(1-mu)+y2*mu; }
871
+
872
+ function drawLine(x, y) {
873
+ x = parseInt(x - chart.getBoundingClientRect().x);
874
+ y = parseInt(y - chart.getBoundingClientRect().y);
875
+ if (md === true && y >= 0 && y < 64 && x >= 0 && x < 256) {
876
+ if (y < 32) {
877
+ a[x] = Math.abs(32-y)*2 + 1;
878
+ chart.childNodes[x].style.height = a[x] + 'px';
879
+ chart.childNodes[x].style.marginTop = y + 'px';
880
+
881
+ for (var i=Math.min(xold, x)+1; i<Math.max(xold, x); i++) {
882
+ l = parseInt(lerp( yold, y, (i-xold)/(x-xold) ));
883
+
884
+ if (l < 32) {
885
+ a[i] = Math.abs(32-l)*2 + 1;
886
+ chart.childNodes[i].style.height = a[i] + 'px';
887
+ chart.childNodes[i].style.marginTop = l + 'px';
888
+ } else if (l < 64) {
889
+ a[i] = Math.abs(l-32)*2 + 1;
890
+ chart.childNodes[i].style.height = a[i] + 'px';
891
+ chart.childNodes[i].style.marginTop = (64-l) + 'px';
892
+ }
893
+ }
894
+ } else if (y < 64) {
895
+ a[x] = Math.abs(y-32)*2 + 1;
896
+ chart.childNodes[x].style.height = a[x] + 'px';
897
+ chart.childNodes[x].style.marginTop = (64-y) + 'px';
898
+
899
+ for (var i=Math.min(xold, x)+1; i<Math.max(xold, x); i++) {
900
+ l = parseInt(lerp( yold, y, (i-xold)/(x-xold) ));
901
+
902
+ if (l < 32) {
903
+ a[i] = Math.abs(32-l)*2 + 1;
904
+ chart.childNodes[i].style.height = a[i] + 'px';
905
+ chart.childNodes[i].style.marginTop = l + 'px';
906
+ } else if (l < 64) {
907
+ a[i] = Math.abs(l-32)*2 + 1;
908
+ chart.childNodes[i].style.height = a[i] + 'px';
909
+ chart.childNodes[i].style.marginTop = (64-l) + 'px';
910
+ }
911
+ }
912
+ }
913
+ blur_in.value = a.join(' ');
914
+ xold = x;
915
+ yold = y;
916
+ chart.title = xold + ',' + yold;
917
+ }
918
+ }
919
+ window.drawLine = drawLine;
920
+
921
+
922
+ window.screenshot = false;
923
+
924
+ function snapshot() {
925
+ if (BABYLON) {
926
+ screenshot = true;
927
+ BABYLON.Engine.LastCreatedScene.getEngine().onEndFrameObservable.add(function() {
928
+ if (screenshot === true) {
929
+ screenshot = false;
930
+ try {
931
+ BABYLON.Tools.CreateScreenshotUsingRenderTarget(BABYLON.Engine.LastCreatedScene.getEngine(), BABYLON.Engine.LastCreatedScene.activeCamera,
932
+ { precision: 1.0 }, (durl) => {
933
+ var cnvs = document.getElementById("model3D").getElementsByTagName("canvas")[0]; //.getContext("webgl2");
934
+ var svgd = `<svg id="svg_out" viewBox="0 0 ` + cnvs.width + ` ` + cnvs.height + `" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
935
+ <defs>
936
+ <filter id="blur" x="0" y="0" xmlns="http://www.w3.org/2000/svg">
937
+ <feGaussianBlur in="SourceGraphic" stdDeviation="1" />
938
+ </filter>
939
+ </defs>
940
+ <image filter="url(#blur)" id="svg_img" x="0" y="0" width="` + cnvs.width + `" height="` + cnvs.height + `" xlink:href=\"` + durl + `\"/>
941
+ </svg>`;
942
+ document.getElementById("cnv_out").width = cnvs.width;
943
+ document.getElementById("cnv_out").height = cnvs.height;
944
+ document.getElementById("img_out").src = "data:image/svg+xml;base64," + btoa(svgd);
945
+ }
946
+ );
947
+ } catch(e) { alert(e); }
948
+ // https://forum.babylonjs.com/t/best-way-to-save-to-jpeg-snapshots-of-scene/17663/11
949
+ }
950
+ });
951
+ }
952
+ }
953
+ window.snapshot = snapshot;
954
+
955
+
956
+ window.recorder = null;
957
+
958
+ function record_video() {
959
+ try {
960
+ if (BABYLON.VideoRecorder.IsSupported(BABYLON.Engine.LastCreatedScene.getEngine()) && (recorder == null || !recorder.isRecording) ) {
961
+ if (recorder == null) {
962
+ recorder = new BABYLON.VideoRecorder(BABYLON.Engine.LastCreatedScene.getEngine(), { mimeType:'video/mp4', fps:25, /*audioTracks: mediaStreamDestination.stream.getAudioTracks()*/ });
963
+ }
964
+ recorder.startRecording('video.mp4', 60*60);
965
+ }
966
+ } catch(e) {alert(e);}
967
+ }
968
+ window.record_video = record_video;
969
+
970
+ function stop_recording() {
971
+ if (recorder.isRecording) {
972
+ recorder.stopRecording();
973
+ }
974
+ }
975
+ window.stop_recording = stop_recording;
976
+
977
+ function seek(t) {
978
+ videoDome.videoTexture.video.currentTime = t;
979
+ if (videoDome.videoTexture.video.currentTime > videoDome.videoTexture.video.duration) {
980
+ videoDome.videoTexture.video.currentTime = videoDome.videoTexture.video.duration;
981
+ } else if (videoDome.videoTexture.video.currentTime < 0) {
982
+ videoDome.videoTexture.video.currentTime = 0;
983
+ }
984
+ video.currentTime = t;
985
+ if (video.currentTime > video.duration) {
986
+ video.currentTime = video.duration;
987
+ } else if (video.currentTime < 0) {
988
+ video.currentTime = 0;
989
+ }
990
+ requestMap();
991
+ }
992
+ window.seek = seek;
993
+
994
+ function videoPlay() {
995
+ videoDome.videoTexture.video.oncanplaythrough = null;
996
+ video.oncanplaythrough = null;
997
+
998
+ videoDome.videoTexture.video.loop = true;
999
+ video.loop = true;
1000
+ videoDome.videoTexture.video.play();
1001
+ video.play();
1002
+ }
1003
+ window.videoPlay = videoPlay;
1004
+
1005
+
1006
+ function applyDisplacementMapFromBuffer(
1007
+ mesh,
1008
+ buffer,
1009
+ heightMapWidth,
1010
+ heightMapHeight,
1011
+ minHeight,
1012
+ maxHeight,
1013
+ uvOffset,
1014
+ uvScale,
1015
+ forceUpdate
1016
+ ) {
1017
+ try {
1018
+ if (!mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
1019
+ let positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
1020
+ let normals = [];
1021
+ BABYLON.VertexData.ComputeNormals(positions, mesh.getIndices(), normals, {useRightHandedSystem: true});
1022
+ mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
1023
+ }
1024
+ const positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
1025
+ const normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
1026
+ const uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
1027
+
1028
+ let position = BABYLON.Vector3.Zero();
1029
+ const normal = BABYLON.Vector3.Zero();
1030
+ const uv = BABYLON.Vector2.Zero();
1031
+
1032
+ uvOffset = uvOffset || BABYLON.Vector2.Zero();
1033
+ uvScale = uvScale || new BABYLON.Vector2(1, 1);
1034
+
1035
+ for (let index = 0; index < positions.length; index += 3) {
1036
+ BABYLON.Vector3.FromArrayToRef(positions, index, position);
1037
+ BABYLON.Vector3.FromArrayToRef(normals, index, normal);
1038
+ BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
1039
+
1040
+ // Compute height
1041
+ const u = (Math.abs(uv.x * uvScale.x + (uvOffset.x % 1)) * (heightMapWidth - 1)) % heightMapWidth | 0;
1042
+ const v = (Math.abs(uv.y * uvScale.y + (uvOffset.y % 1)) * (heightMapHeight - 1)) % heightMapHeight | 0;
1043
+
1044
+ const pos = (u + v * heightMapWidth) * 4;
1045
+ const r = buffer[pos] / 255.0;
1046
+ const g = buffer[pos + 1] / 255.0;
1047
+ const b = buffer[pos + 2] / 255.0;
1048
+ const a = buffer[pos + 3] / 255.0;
1049
+
1050
+ const gradient = r * 0.33 + g * 0.33 + b * 0.33;
1051
+ //const gradient = a;
1052
+
1053
+ normal.normalize();
1054
+ normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
1055
+ position = position.add(normal);
1056
+
1057
+ position.toArray(positions, index);
1058
+ }
1059
+ mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
1060
+
1061
+ return mesh;
1062
+ } catch(e) {alert(e)}
1063
+ }
1064
+ window.applyDisplacementMapFromBuffer = applyDisplacementMapFromBuffer;
1065
+
1066
+
1067
+ var intv_ = setInterval(function(){
1068
+ if (document.getElementById("image_edit") && document.getElementById("image_edit").getElementsByTagName("canvas")) {
1069
+ document.getElementById("image_edit").getElementsByTagName("canvas")[0].oncontextmenu = function(e){e.preventDefault();}
1070
+ document.getElementById("image_edit").getElementsByTagName("canvas")[0].ondrag = function(e){e.preventDefault();}
1071
+
1072
+ document.getElementById("image_edit").getElementsByTagName("canvas")[0].onclick = function(e) {
1073
+ var x = parseInt((e.clientX-e.target.getBoundingClientRect().x)*e.target.width/e.target.getBoundingClientRect().width);
1074
+ var y = parseInt((e.clientY-e.target.getBoundingClientRect().y)*e.target.height/e.target.getBoundingClientRect().height);
1075
+
1076
+ var p = document.getElementById("mouse").getElementsByTagName("textarea")[0].value.slice(1, -1);
1077
+ if (p != "") { p += ", "; }
1078
+ p += "[" + x + ", " + y + "]";
1079
+ document.getElementById("mouse").getElementsByTagName("textarea")[0].value = "[" + p + "]";
1080
+
1081
+ var evt = document.createEvent("Event");
1082
+ evt.initEvent("input", true, false);
1083
+ document.getElementById("mouse").getElementsByTagName("textarea")[0].dispatchEvent(evt);
1084
+ }
1085
+ document.getElementById("image_edit").getElementsByTagName("canvas")[0].onfocus = function(e) {
1086
+ document.getElementById("mouse").getElementsByTagName("textarea")[0].value = "[]";
1087
+ }
1088
+ document.getElementById("image_edit").getElementsByTagName("canvas")[0].onblur = function(e) {
1089
+ document.getElementById("mouse").getElementsByTagName("textarea")[0].value = "[]";
1090
+ }
1091
+ clearInterval(intv_);
1092
+ }
1093
+ }, 40);
1094
+
1095
+ }
1096
+ """
1097
+
1098
+ css = """
1099
+ #img-display-container {
1100
+ max-height: 100vh;
1101
+ }
1102
+ #img-display-input {
1103
+ max-height: 80vh;
1104
+ }
1105
+ #img-display-output {
1106
+ max-height: 80vh;
1107
+ }
1108
+ """
1109
+
1110
+ head = """
1111
+ """
1112
+
1113
+ title = "# Depth Anything V2 Video"
1114
+ description = """**Depth Anything V2** on full video files, intended for Google Street View panorama slideshows.
1115
+ Please refer to the [paper](https://arxiv.org/abs/2406.09414), [project page](https://depth-anything-v2.github.io), and [github](https://github.com/DepthAnything/Depth-Anything-V2) for more details."""
1116
+
1117
+
1118
+ #transform = Compose([
1119
+ # Resize(
1120
+ # width=518,
1121
+ # height=518,
1122
+ # resize_target=False,
1123
+ # keep_aspect_ratio=True,
1124
+ # ensure_multiple_of=14,
1125
+ # resize_method='lower_bound',
1126
+ # image_interpolation_method=cv2.INTER_CUBIC,
1127
+ # ),
1128
+ # NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
1129
+ # PrepareForNet(),
1130
+ #])
1131
+
1132
+ # @torch.no_grad()
1133
+ # def predict_depth(model, image):
1134
+ # return model(image)
1135
+
1136
+ with gr.Blocks(css=css, js=js, head=head) as demo:
1137
+ gr.Markdown(title)
1138
+ gr.Markdown(description)
1139
+ gr.Markdown("### Video Depth Prediction demo")
1140
+
1141
+ with gr.Row():
1142
+ with gr.Column():
1143
+ with gr.Group():
1144
+ input_json = gr.Textbox(elem_id="json_in", value="{}", label="JSON", interactive=False)
1145
+ input_url = gr.Textbox(elem_id="url_in", value="./examples/streetview.mp4", label="URL")
1146
+ input_video = gr.Video(label="Input Video", format="mp4")
1147
+ input_url.input(fn=loadfile, inputs=[input_url], outputs=[input_video])
1148
+ submit = gr.Button("Submit")
1149
+ with gr.Group():
1150
+ output_frame = gr.Gallery(label="Frames", preview=True, columns=8192, interactive=False)
1151
+ output_switch = gr.Checkbox(label="Show depths")
1152
+ output_switch.input(fn=switch_rows, inputs=[output_switch], outputs=[output_frame])
1153
+ selected = gr.Number(label="Selected frame", visible=False, elem_id="fnum", value=0, minimum=0, maximum=256, interactive=False)
1154
+ with gr.Accordion(label="Depths", open=False):
1155
+ output_depth = gr.Files(label="Depth files", interactive=False)
1156
+ with gr.Group():
1157
+ output_mask = gr.ImageEditor(layers=False, sources=('clipboard'), show_download_button=True, type="numpy", interactive=True, transforms=(None,), eraser=gr.Eraser(), brush=gr.Brush(default_size=0, colors=['black', '#505050', '#a0a0a0', 'white']), elem_id="image_edit")
1158
+ with gr.Accordion(label="Border", open=False):
1159
+ boffset = gr.Slider(label="Inner", value=1, maximum=256, minimum=0, step=1)
1160
+ bsize = gr.Slider(label="Outer", value=32, maximum=256, minimum=0, step=1)
1161
+ mouse = gr.Textbox(label="Mouse x,y", elem_id="mouse", value="""[]""", interactive=False)
1162
+ reset = gr.Button("Reset", size='sm')
1163
+ mouse.input(fn=draw_mask, show_progress="minimal", inputs=[boffset, bsize, mouse, output_mask], outputs=[output_mask])
1164
+ reset.click(fn=reset_mask, inputs=[output_mask], outputs=[output_mask])
1165
+
1166
+ with gr.Column():
1167
+ model_type = gr.Dropdown([("small", "vits"), ("base", "vitb"), ("large", "vitl"), ("giant", "vitg")], type="value", value="vits", label='Model Type')
1168
+ processed_video = gr.Video(label="Output Video", format="mp4", elem_id="output_video", interactive=False)
1169
+ processed_zip = gr.File(label="Output Archive", interactive=False)
1170
+ depth_video = gr.Video(label="Depth Video", format="mp4", elem_id="depth_video", interactive=False, visible=True)
1171
+ result = gr.Model3D(label="3D Mesh", clear_color=[0.5, 0.5, 0.5, 0.0], camera_position=[0, 90, 512], zoom_speed=2.0, pan_speed=2.0, interactive=True, elem_id="model3D")
1172
+ with gr.Accordion(label="Embed in website", open=False):
1173
+ embed_model = gr.Textbox(elem_id="embed_model", label="Include this wherever the model is to appear on the page", interactive=False, value="""
1174
+
1175
+ """)
1176
+
1177
+ with gr.Tab("Blur"):
1178
+ chart_c = gr.HTML(elem_id="chart_c", value="""<div id='chart' onpointermove='window.drawLine(event.clientX, event.clientY);' onpointerdown='window.pointerDown(event.clientX, event.clientY);' onpointerup='window.pointerUp();' onpointerleave='window.pointerUp();' onpointercancel='window.pointerUp();' onclick='window.resetLine();'></div>
1179
+ <style>
1180
+ * {
1181
+ user-select: none;
1182
+ }
1183
+ html, body {
1184
+ user-select: none;
1185
+ }
1186
+ #model3D canvas {
1187
+ user-select: none;
1188
+ }
1189
+ #chart hr {
1190
+ width: 1px;
1191
+ height: 1px;
1192
+ clear: none;
1193
+ border: 0;
1194
+ padding:0;
1195
+ display: inline-block;
1196
+ position: relative;
1197
+ vertical-align: top;
1198
+ margin-top:32px;
1199
+ }
1200
+ #chart {
1201
+ padding:0;
1202
+ margin:0;
1203
+ width:256px;
1204
+ height:64px;
1205
+ background-color:#808080;
1206
+ touch-action: none;
1207
+ }
1208
+ #compass_box {
1209
+ position:absolute;
1210
+ top:2em;
1211
+ right:3px;
1212
+ border:1px dashed gray;
1213
+ border-radius: 50%;
1214
+ width:1.5em;
1215
+ height:1.5em;
1216
+ padding:0;
1217
+ margin:0;
1218
+ }
1219
+ #compass {
1220
+ position:absolute;
1221
+ transform:rotate(0deg);
1222
+ border:1px solid black;
1223
+ border-radius: 50%;
1224
+ width:100%;
1225
+ height:100%;
1226
+ padding:0;
1227
+ margin:0;
1228
+ line-height:1em;
1229
+ letter-spacing:0;
1230
+ }
1231
+ #compass b {
1232
+ margin-top:-1px;
1233
+ }
1234
+ </style>
1235
+ """)
1236
+ average = gr.HTML(value="""<label for='average'>Average</label><input id='average' type='range' style='width:256px;height:1em;' value='1' min='1' max='15' step='2' onclick='
1237
+ var pts_a = document.getElementById(\"blur_in\").getElementsByTagName(\"textarea\")[0].value.split(\" \");
1238
+ for (var i=0; i<256; i++) {
1239
+ var avg = 0;
1240
+ var div = this.value;
1241
+ for (var j = i-parseInt(this.value/2); j <= i+parseInt(this.value/2); j++) {
1242
+ if (pts_a[j]) {
1243
+ avg += parseInt(pts_a[j]);
1244
+ } else if (div > 1) {
1245
+ div--;
1246
+ }
1247
+ }
1248
+ pts_a[i] = Math.round((avg / div - 1) / 2) * 2 + 1;
1249
+
1250
+ document.getElementById(\"chart\").childNodes[i].style.height = pts_a[i] + \"px\";
1251
+ document.getElementById(\"chart\").childNodes[i].style.marginTop = (64-pts_a[i])/2 + \"px\";
1252
+ }
1253
+ document.getElementById(\"blur_in\").getElementsByTagName(\"textarea\")[0].value = pts_a.join(\" \");
1254
+
1255
+ var evt = document.createEvent(\"Event\");
1256
+ evt.initEvent(\"input\", true, false);
1257
+ document.getElementById(\"blur_in\").getElementsByTagName(\"textarea\")[0].dispatchEvent(evt);
1258
+ ' oninput='
1259
+ this.parentNode.childNodes[2].innerText = this.value;
1260
+ ' onchange='this.click();'/><span>1</span>""")
1261
+ with gr.Accordion(label="Levels", open=False):
1262
+ blur_in = gr.Textbox(elem_id="blur_in", label="Kernel size", show_label=False, interactive=False, value=blurin)
1263
+ with gr.Group():
1264
+ with gr.Accordion(label="Locations", open=False):
1265
+ output_frame.select(fn=select_frame, inputs=[output_mask], outputs=[output_mask, selected])
1266
+ example_coords = """[
1267
+ {"lat": 50.07379596793083, "lng": 14.437146122950555, "heading": 152.70303, "pitch": 2.607833999999997},
1268
+ {"lat": 50.073799567020004, "lng": 14.437146774240507, "heading": 151.12973, "pitch": 2.8672300000000064},
1269
+ {"lat": 50.07377647505558, "lng": 14.437161000659017, "heading": 151.41025, "pitch": 3.4802200000000028},
1270
+ {"lat": 50.07379496839027, "lng": 14.437148958238538, "heading": 151.93391, "pitch": 2.843050000000005},
1271
+ {"lat": 50.073823157821664, "lng": 14.437124189538856, "heading": 152.95769, "pitch": 4.233024999999998}
1272
+ ]"""
1273
+ coords = gr.Textbox(elem_id="coords", value=example_coords, label="Coordinates", interactive=False)
1274
+ mesh_order = gr.Textbox(elem_id="order", value="", label="Order", interactive=False)
1275
+ load_all = gr.Checkbox(label="Load all")
1276
+
1277
+ with gr.Group():
1278
+ camera = gr.HTML(value="""<div style='width:128px;height:128px;border:1px dotted gray;padding:0;margin:0;float:left;clear:none;' id='seek'></div>
1279
+ <span style='max-width:50%;float:right;clear:none;text-align:right;'>
1280
+ <a href='#' id='reset_cam' style='float:right;clear:none;color:white' onclick='
1281
+ if (!BABYLON.Engine.LastCreatedScene.activeCamera.metadata) {
1282
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata = {
1283
+ screenshot: true,
1284
+ pipeline: new BABYLON.DefaultRenderingPipeline(\"default\", true, BABYLON.Engine.LastCreatedScene, [BABYLON.Engine.LastCreatedScene.activeCamera])
1285
+ }
1286
+ }
1287
+ BABYLON.Engine.LastCreatedScene.activeCamera.radius = 0;
1288
+ BABYLON.Engine.LastCreatedScene.activeCamera.alpha = 0;
1289
+ BABYLON.Engine.LastCreatedScene.activeCamera.beta = Math.PI / 2;
1290
+
1291
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.samples = 4;
1292
+ BABYLON.Engine.LastCreatedScene.activeCamera.fov = document.getElementById(\"zoom\").value;
1293
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.imageProcessing.contrast = document.getElementById(\"contrast\").value;
1294
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.imageProcessing.exposure = document.getElementById(\"exposure\").value;
1295
+
1296
+ document.getElementById(\"model3D\").getElementsByTagName(\"canvas\")[0].style.filter = \"blur(\" + Math.ceil(Math.log2(Math.PI/document.getElementById(\"zoom\").value))/2.0*Math.sqrt(2.0) + \"px)\";
1297
+ document.getElementById(\"model3D\").getElementsByTagName(\"canvas\")[0].oncontextmenu = function(e){e.preventDefault();}
1298
+ document.getElementById(\"model3D\").getElementsByTagName(\"canvas\")[0].ondrag = function(e){e.preventDefault();}
1299
+ '>Reset camera</a><br/>
1300
+ <span><label for='zoom' style='width:8em'>Zoom</label><input id='zoom' type='range' style='width:128px;height:1em;' value='0.8' min='0.157' max='1.57' step='0.001' oninput='
1301
+ if (!BABYLON.Engine.LastCreatedScene.activeCamera.metadata) {
1302
+ var evt = document.createEvent(\"Event\");
1303
+ evt.initEvent(\"click\", true, false);
1304
+ document.getElementById(\"reset_cam\").dispatchEvent(evt);
1305
+ }
1306
+ BABYLON.Engine.LastCreatedScene.activeCamera.fov = this.value;
1307
+ this.parentNode.childNodes[2].innerText = BABYLON.Engine.LastCreatedScene.activeCamera.fov;
1308
+
1309
+ document.getElementById(\"model3D\").getElementsByTagName(\"canvas\")[0].style.filter = \"blur(\" + BABYLON.Engine.LastCreatedScene.getNodes()[parseInt(document.getElementById(\"fnum\").getElementsByTagName(\"input\")[0].value)+1].material.pointSize/2.0*Math.sqrt(2.0) + \"px)\";
1310
+ '/><span>0.8</span></span><br/>
1311
+ <span><label for='pan' style='width:8em'>Pan</label><input id='pan' type='range' style='width:128px;height:1em;' value='0' min='-16' max='16' step='0.001' oninput='
1312
+ if (!BABYLON.Engine.LastCreatedScene.activeCamera.metadata) {
1313
+ var evt = document.createEvent(\"Event\");
1314
+ evt.initEvent(\"click\", true, false);
1315
+ document.getElementById(\"reset_cam\").dispatchEvent(evt);
1316
+ }
1317
+ parallax = this.value;
1318
+ rdir = BABYLON.Engine.LastCreatedScene.activeCamera.getDirection(xdir);
1319
+ videoDomeMesh.position.x = parallax * rdir.x;
1320
+ videoDomeMesh.position.z = parallax * rdir.z;
1321
+ this.parentNode.childNodes[2].innerText = parallax;
1322
+ '/><span>0.0</span></span><br/>
1323
+ <span><label for='contrast' style='width:8em'>Contrast</label><input id='contrast' type='range' style='width:128px;height:1em;' value='1.0' min='0' max='2' step='0.001' oninput='
1324
+ if (!BABYLON.Engine.LastCreatedScene.activeCamera.metadata) {
1325
+ var evt = document.createEvent(\"Event\");
1326
+ evt.initEvent(\"click\", true, false);
1327
+ document.getElementById(\"reset_cam\").dispatchEvent(evt);
1328
+ }
1329
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.imageProcessing.contrast = this.value;
1330
+ this.parentNode.childNodes[2].innerText = BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.imageProcessing.contrast;
1331
+ '/><span>1.0</span></span><br/>
1332
+ <span><label for='exposure' style='width:8em'>Exposure</label><input id='exposure' type='range' style='width:128px;height:1em;' value='1.0' min='0' max='2' step='0.001' oninput='
1333
+ if (!BABYLON.Engine.LastCreatedScene.activeCamera.metadata) {
1334
+ var evt = document.createEvent(\"Event\");
1335
+ evt.initEvent(\"click\", true, false);
1336
+ document.getElementById(\"reset_cam\").dispatchEvent(evt);
1337
+ }
1338
+ BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.imageProcessing.exposure = this.value;
1339
+ this.parentNode.childNodes[2].innerText = BABYLON.Engine.LastCreatedScene.activeCamera.metadata.pipeline.imageProcessing.exposure;
1340
+ '/><span>1.0</span></span><br/>
1341
+ <a href='#' onclick='snapshot();'>Screenshot</a>
1342
+ <a href='#' onclick='record_video();'>Record</a>
1343
+ <a href='#' onclick='stop_recording();'>Stop rec.</a>
1344
+ <a href='#' onclick='videoPlay();'>Play</a></span>""")
1345
+ snapshot = gr.HTML(value="""<img src='' id='img_out' onload='var ctxt = document.getElementById(\"cnv_out\").getContext(\"2d\");ctxt.drawImage(this, 0, 0);'/><br/>
1346
+ <canvas id='cnv_out'></canvas>
1347
+ <div id='compass_box'><div id='compass'><a id='fullscreen' onclick='
1348
+ const model3D = document.getElementById(\"model3D\");
1349
+ if (model3D.parentNode.tagName != \"BODY\") {
1350
+ window.modelContainer = model3D.parentNode.id;
1351
+ document.body.appendChild(model3D);
1352
+ model3D.style.position = \"fixed\";
1353
+ model3D.style.left = \"0\";
1354
+ model3D.style.top = \"0\";
1355
+ model3D.style.zIndex = \"100\";
1356
+ document.getElementById(\"compass_box\").style.zIndex = \"101\";
1357
+ } else {
1358
+ document.getElementById(window.modelContainer).appendChild(model3D);
1359
+ model3D.style.position = \"relative\";
1360
+ model3D.style.left = \"0\";
1361
+ model3D.style.top = \"0\";
1362
+ model3D.style.zIndex = \"initial\";
1363
+ document.getElementById(\"compass_box\").style.zIndex = \"initial\";
1364
+ }'><b style='color:blue;'>◅</b>𝍠<b style='color:red;'>▻</b></a></div>
1365
+ </div>
1366
+ """)
1367
+ render = gr.Button("Render")
1368
+ input_json.input(show_json, inputs=[input_json], outputs=[processed_video, processed_zip, output_frame, output_mask, output_depth, coords])
1369
+
1370
+
1371
+ def on_submit(uploaded_video,model_type,blur_in,boffset,bsize,coordinates):
1372
+ global locations
1373
+ locations = []
1374
+ avg = [0, 0]
1375
+
1376
+ locations = json.loads(coordinates)
1377
+ for k, location in enumerate(locations):
1378
+ if "tiles" in locations[k]:
1379
+ locations[k]["heading"] = locations[k]["tiles"]["originHeading"]
1380
+ locations[k]["pitch"] = locations[k]["tiles"]["originPitch"]
1381
+ elif not "heading" in locations[k] or not "pitch" in locations[k]:
1382
+ locations[k]["heading"] = 0.0
1383
+ locations[k]["pitch"] = 0.0
1384
+
1385
+ if "location" in locations[k]:
1386
+ locations[k] = locations[k]["location"]["latLng"]
1387
+ elif not "lat" in locations[k] or not "lng" in locations[k]:
1388
+ locations[k]["lat"] = 0.0
1389
+ locations[k]["lng"] = 0.0
1390
+
1391
+ avg[0] = avg[0] + locations[k]["lat"]
1392
+ avg[1] = avg[1] + locations[k]["lng"]
1393
+
1394
+ if len(locations) > 0:
1395
+ avg[0] = avg[0] / len(locations)
1396
+ avg[1] = avg[1] / len(locations)
1397
+
1398
+ for k, location in enumerate(locations):
1399
+ lat = vincenty((location["lat"], 0), (avg[0], 0)) * 1000
1400
+ lng = vincenty((0, location["lng"]), (0, avg[1])) * 1000
1401
+ locations[k]["lat"] = float(lat / 2.5 * 111 * np.sign(location["lat"]-avg[0]))
1402
+ locations[k]["lng"] = float(lng / 2.5 * 111 * np.sign(location["lng"]-avg[1]))
1403
+ print(locations)
1404
+ # 2.5m is height of camera on google street view car,
1405
+ # distance from center of sphere to pavement roughly 255 - 144 = 111 units
1406
+
1407
+ # Process the video and get the path of the output video
1408
+ output_video_path = make_video(uploaded_video,encoder=model_type,blur_data=blurin,o=boffset,b=bsize)
1409
+
1410
+ return output_video_path + (json.dumps(locations),)
1411
+
1412
+ submit.click(on_submit, inputs=[input_video, model_type, blur_in, boffset, bsize, coords], outputs=[processed_video, processed_zip, output_frame, output_mask, output_depth, depth_video, coords])
1413
+ render.click(None, inputs=[coords, mesh_order, output_frame, output_mask, selected, output_depth, output_switch], outputs=None, js=load_model)
1414
+ render.click(partial(get_mesh), inputs=[output_frame, output_mask, blur_in, load_all], outputs=[result, mesh_order])
1415
+
1416
+ example_files = [["./examples/streetview.mp4", "vits", blurin, 1, 32, example_coords]]
1417
+ examples = gr.Examples(examples=example_files, fn=on_submit, cache_examples=True, inputs=[input_video, model_type, blur_in, boffset, bsize, coords], outputs=[processed_video, processed_zip, output_frame, output_mask, output_depth, depth_video, coords])
1418
+
1419
+
1420
+ if __name__ == '__main__':
1421
+ demo.queue().launch()