Shariq F. Bhat commited on
Commit ·
99b3515
1
Parent(s): 3622d44
initial release
Browse filesFiles changed (19)
- .gitattributes+1
- .gitignoreAdded+2
- app.pyAdded+42
- examples/aerial_beach.jpegAdded
- examples/ancient-carved.jpegAdded
- examples/living-room.jpegAdded
- examples/mountains.jpegAdded
- examples/pano_1.jpegAdded
- examples/pano_2.jpegAdded
- examples/pano_3.jpegAdded
- examples/person-leaves.pngAdded
- examples/person_1.jpegAdded
- examples/person_2.jpegAdded
- geometry.pyAdded+72
- gradio_depth_pred.pyAdded+28
- gradio_im_to_3d.pyAdded+69
- gradio_pano_to_3d.pyAdded+96
- requirements.txtAdded+4
- utils.pyAdded+86
31 unmodified lines32333431 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text31 unmodified lines3233343531 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/person-leaves.png filter=lfs diff=lfs merge=lfs -text
12__pycache__/**.pyc123456789101112131415161718192021222324252627282930313233343536373839404142import gradio as grimport torch
from gradio_depth_pred import create_demo as create_depth_pred_demofrom gradio_im_to_3d import create_demo as create_im_to_3d_demofrom gradio_pano_to_3d import create_demo as create_pano_to_3d_demo
css = """#img-display-container { max-height: 50vh; }#img-display-input { max-height: 40vh; }#img-display-output { max-height: 40vh; } """DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'model = torch.hub.load('isl-org/ZoeDepth', "ZoeD_N", pretrained=True).to(DEVICE).eval()
title = "# ZoeDepth"description = """Official demo for **ZoeDepth: Zero-shot Transfer by Combining Relative and Metric Depth**.
ZoeDepth is a deep learning model for metric depth estimation from a single image.
Please refer to our [paper](https://arxiv.org/abs/2302.12288) or [github](https://github.com/isl-org/ZoeDepth) for more details."""
with gr.Blocks(css=css) as demo: gr.Markdown(title) gr.Markdown(description) with gr.Tab("Depth Prediction"): create_depth_pred_demo(model) with gr.Tab("Image to 3D"): create_im_to_3d_demo(model) with gr.Tab("360 Panorama to 3D"): create_pano_to_3d_demo(model)
if __name__ == '__main__': demo.queue().launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import numpy as np
def get_intrinsics(H,W): """ Intrinsics for a pinhole camera model. Assume fov of 55 degrees and central principal point. """ f = 0.5 * W / np.tan(0.5 * 55 * np.pi / 180.0) cx = 0.5 * W cy = 0.5 * H return np.array([[f, 0, cx], [0, f, cy], [0, 0, 1]])
def depth_to_points(depth, R=None, t=None):
K = get_intrinsics(depth.shape[1], depth.shape[2]) Kinv = np.linalg.inv(K) if R is None: R = np.eye(3) if t is None: t = np.zeros(3)
# M converts from your coordinate to PyTorch3D's coordinate system M = np.eye(3) M[0, 0] = -1.0 M[1, 1] = -1.0
height, width = depth.shape[1:3]
x = np.arange(width) y = np.arange(height) coord = np.stack(np.meshgrid(x, y), -1) coord = np.concatenate((coord, np.ones_like(coord)[:, :, [0]]), -1) # z=1 coord = coord.astype(np.float32) # coord = torch.as_tensor(coord, dtype=torch.float32, device=device) coord = coord[None] # bs, h, w, 3
D = depth[:, :, :, None, None] # print(D.shape, Kinv[None, None, None, ...].shape, coord[:, :, :, :, None].shape ) pts3D_1 = D * Kinv[None, None, None, ...] @ coord[:, :, :, :, None] # pts3D_1 live in your coordinate system. Convert them to Py3D's pts3D_1 = M[None, None, None, ...] @ pts3D_1 # from reference to targe tviewpoint pts3D_2 = R[None, None, None, ...] @ pts3D_1 + t[None, None, None, :, None] # pts3D_2 = pts3D_1 # depth_2 = pts3D_2[:, :, :, 2, :] # b,1,h,w return pts3D_2[:, :, :, :3, 0][0]
def create_triangles(h, w, mask=None): """Creates mesh triangle indices from a given pixel grid size. This function is not and need not be differentiable as triangle indices are fixed. Args: h: (int) denoting the height of the image. w: (int) denoting the width of the image. Returns: triangles: 2D numpy array of indices (int) with shape (2(W-1)(H-1) x 3) """ x, y = np.meshgrid(range(w - 1), range(h - 1)) tl = y * w + x tr = y * w + x + 1 bl = (y + 1) * w + x br = (y + 1) * w + x + 1 triangles = np.array([tl, bl, tr, br, tr, bl]) triangles = np.transpose(triangles, (1, 2, 0)).reshape( ((w - 1) * (h - 1) * 2, 3)) if mask is not None: mask = mask.reshape(-1) triangles = triangles[mask[triangles].all(1)] return triangles12345678910111213141516171819202122232425262728import gradio as grfrom utils import colorizefrom PIL import Imageimport tempfile
def predict_depth(model, image): depth = model.infer_pil(image) return depth
def create_demo(model): gr.Markdown("### Depth Prediction demo") with gr.Row(): input_image = gr.Image(label="Input Image", type='pil', elem_id='img-display-input').style(height="auto") depth_image = gr.Image(label="Depth Map", elem_id='img-display-output') raw_file = gr.File(label="16-bit raw depth, multiplier:256") submit = gr.Button("Submit")
def on_submit(image): depth = predict_depth(model, image) colored_depth = colorize(depth, cmap='gray_r') tmp = tempfile.NamedTemporaryFile(suffix='.png', delete=False) raw_depth = Image.fromarray((depth*256).astype('uint16')) raw_depth.save(tmp.name) return [colored_depth, tmp.name] submit.click(on_submit, inputs=[input_image], outputs=[depth_image, raw_file]) examples = gr.Examples(examples=["examples/person_1.jpeg", "examples/person_2.jpeg", "examples/person-leaves.png", "examples/living-room.jpeg"], inputs=[input_image])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import gradio as grimport numpy as npimport trimeshfrom geometry import depth_to_points, create_trianglesfrom functools import partialimport tempfile
def depth_edges_mask(depth): """Returns a mask of edges in the depth map. Args: depth: 2D numpy array of shape (H, W) with dtype float32. Returns: mask: 2D numpy array of shape (H, W) with dtype bool. """ # Compute the x and y gradients of the depth map. depth_dx, depth_dy = np.gradient(depth) # Compute the gradient magnitude. depth_grad = np.sqrt(depth_dx ** 2 + depth_dy ** 2) # Compute the edge mask. mask = depth_grad > 0.05 return mask
def predict_depth(model, image): depth = model.infer_pil(image) return depth
def get_mesh(model, image, keep_edges=False): image.thumbnail((1024,1024)) # limit the size of the input image depth = predict_depth(model, image) pts3d = depth_to_points(depth[None]) pts3d = pts3d.reshape(-1, 3)
# Create a trimesh mesh from the points # Each pixel is connected to its 4 neighbors # colors are the RGB values of the image
verts = pts3d.reshape(-1, 3) image = np.array(image) if keep_edges: triangles = create_triangles(image.shape[0], image.shape[1]) else: triangles = create_triangles(image.shape[0], image.shape[1], mask=~depth_edges_mask(depth)) colors = image.reshape(-1, 3) mesh = trimesh.Trimesh(vertices=verts, faces=triangles, vertex_colors=colors)
# Save as glb glb_file = tempfile.NamedTemporaryFile(suffix='.glb', delete=False) glb_path = glb_file.name mesh.export(glb_path) return glb_path
def create_demo(model):
gr.Markdown("### Image to 3D mesh") gr.Markdown("Convert a single 2D image to a 3D mesh")
with gr.Row(): image = gr.Image(label="Input Image", type='pil') result = gr.Model3D(label="3d mesh reconstruction", clear_color=[ 1.0, 1.0, 1.0, 1.0]) checkbox = gr.Checkbox(label="Keep occlusion edges", value=False) submit = gr.Button("Submit") submit.click(partial(get_mesh, model), inputs=[image, checkbox], outputs=[result]) examples = gr.Examples(examples=["examples/aerial_beach.jpeg", "examples/mountains.jpeg", "examples/person_1.jpeg", "examples/ancient-carved.jpeg"], inputs=[image])
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import gradio as grimport numpy as npimport trimeshfrom geometry import create_trianglesfrom functools import partialimport tempfile
def depth_edges_mask(depth): """Returns a mask of edges in the depth map. Args: depth: 2D numpy array of shape (H, W) with dtype float32. Returns: mask: 2D numpy array of shape (H, W) with dtype bool. """ # Compute the x and y gradients of the depth map. depth_dx, depth_dy = np.gradient(depth) # Compute the gradient magnitude. depth_grad = np.sqrt(depth_dx ** 2 + depth_dy ** 2) # Compute the edge mask. mask = depth_grad > 0.05 return mask
def pano_depth_to_world_points(depth): """ 360 depth to world points given 2D depth is an equirectangular projection of a spherical image Treat depth as radius
longitude : -pi to pi latitude : -pi/2 to pi/2 """
# Convert depth to radius radius = depth.flatten()
lon = np.linspace(-np.pi, np.pi, depth.shape[1]) lat = np.linspace(-np.pi/2, np.pi/2, depth.shape[0])
lon, lat = np.meshgrid(lon, lat) lon = lon.flatten() lat = lat.flatten()
# Convert to cartesian coordinates x = radius * np.cos(lat) * np.cos(lon) y = radius * np.cos(lat) * np.sin(lon) z = radius * np.sin(lat)
pts3d = np.stack([x, y, z], axis=1)
return pts3d
def predict_depth(model, image): depth = model.infer_pil(image) return depth
def get_mesh(model, image, keep_edges=False): image.thumbnail((1024,1024)) # limit the size of the image depth = predict_depth(model, image) pts3d = pano_depth_to_world_points(depth)
# Create a trimesh mesh from the points # Each pixel is connected to its 4 neighbors # colors are the RGB values of the image
verts = pts3d.reshape(-1, 3) image = np.array(image) if keep_edges: triangles = create_triangles(image.shape[0], image.shape[1]) else: triangles = create_triangles(image.shape[0], image.shape[1], mask=~depth_edges_mask(depth)) colors = image.reshape(-1, 3) mesh = trimesh.Trimesh(vertices=verts, faces=triangles, vertex_colors=colors)
# Save as glb glb_file = tempfile.NamedTemporaryFile(suffix='.glb', delete=False) glb_path = glb_file.name mesh.export(glb_path) return glb_path
def create_demo(model): gr.Markdown("### Panorama to 3D mesh") gr.Markdown("Convert a 360 spherical panorama to a 3D mesh") gr.Markdown("ZoeDepth was not trained on panoramic images. It doesn't know anything about panoramas or spherical projection. Here, we just treat the estimated depth as radius and some projection errors are expected. Nonetheless, ZoeDepth still works surprisingly well on 360 reconstruction.")
with gr.Row(): input_image = gr.Image(label="Input Image", type='pil') result = gr.Model3D(label="3d mesh reconstruction", clear_color=[ 1.0, 1.0, 1.0, 1.0]) checkbox = gr.Checkbox(label="Keep occlusion edges", value=True) submit = gr.Button("Submit") submit.click(partial(get_mesh, model), inputs=[input_image, checkbox], outputs=[result]) examples = gr.Examples(examples=["examples/pano_1.jpeg", "examples/pano_2.jpeg", "examples/pano_3.jpeg"], inputs=[input_image])1234timm==0.6.11torch==1.10.1torchvision==0.11.2trimesh==3.9.421234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy# of this software and associated documentation files (the "Software"), to deal# in the Software without restriction, including without limitation the rights# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# copies of the Software, and to permit persons to whom the Software is# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE# SOFTWARE.
# File author: Shariq Farooq Bhat
import matplotlibimport matplotlib.cmimport numpy as npimport torch
def colorize(value, vmin=None, vmax=None, cmap='magma_r', invalid_val=-99, invalid_mask=None, background_color=(128, 128, 128, 255), gamma_corrected=False, value_transform=None): """Converts a depth map to a color image.
Args: value (torch.Tensor, numpy.ndarry): Input depth map. Shape: (H, W) or (1, H, W) or (1, 1, H, W). All singular dimensions are squeezed vmin (float, optional): vmin-valued entries are mapped to start color of cmap. If None, value.min() is used. Defaults to None. vmax (float, optional): vmax-valued entries are mapped to end color of cmap. If None, value.max() is used. Defaults to None. cmap (str, optional): matplotlib colormap to use. Defaults to 'magma_r'. invalid_val (int, optional): Specifies value of invalid pixels that should be colored as 'background_color'. Defaults to -99. invalid_mask (numpy.ndarray, optional): Boolean mask for invalid regions. Defaults to None. background_color (tuple[int], optional): 4-tuple RGB color to give to invalid pixels. Defaults to (128, 128, 128, 255). gamma_corrected (bool, optional): Apply gamma correction to colored image. Defaults to False. value_transform (Callable, optional): Apply transform function to valid pixels before coloring. Defaults to None.
Returns: numpy.ndarray, dtype - uint8: Colored depth map. Shape: (H, W, 4) """ if isinstance(value, torch.Tensor): value = value.detach().cpu().numpy()
value = value.squeeze() if invalid_mask is None: invalid_mask = value == invalid_val mask = np.logical_not(invalid_mask)
# normalize vmin = np.percentile(value[mask],2) if vmin is None else vmin vmax = np.percentile(value[mask],85) if vmax is None else vmax if vmin != vmax: value = (value - vmin) / (vmax - vmin) # vmin..vmax else: # Avoid 0-division value = value * 0.
# squeeze last dim if it exists # grey out the invalid values
value[invalid_mask] = np.nan cmapper = matplotlib.cm.get_cmap(cmap) if value_transform: value = value_transform(value) # value = value / value.max() value = cmapper(value, bytes=True) # (nxmx4)
# img = value[:, :, :] img = value[...] img[invalid_mask] = background_color
# return img.transpose((2, 0, 1)) if gamma_corrected: # gamma correction img = img / 255 img = np.power(img, 2.2) img = img * 255 img = img.astype(np.uint8) return img
.gitattributes+1
.gitignoreAdded+2
app.pyAdded+42
examples/aerial_beach.jpegAdded

examples/ancient-carved.jpegAdded

examples/living-room.jpegAdded

examples/mountains.jpegAdded

examples/pano_1.jpegAdded

examples/pano_2.jpegAdded

examples/pano_3.jpegAdded

examples/person-leaves.pngAdded

Large File Pointer Details
- SHA256: 00791e189fd3df0b963288332a944c420a606891aba7cc2d6356bdd7378fbb7b
- Pointer size: 132 Bytes
- Size of remote file: 1.18 MB
examples/person_1.jpegAdded

examples/person_2.jpegAdded

geometry.pyAdded+72
gradio_depth_pred.pyAdded+28
gradio_im_to_3d.pyAdded+69
gradio_pano_to_3d.pyAdded+96
requirements.txtAdded+4
utils.pyAdded+86