CoolFace
Apppublic

nev/depthapi

sourceHugging Facemitupdated 3y agoView on Hugging Face
1likes
app.py65 linesDownload Raw Back to root
1from depth import MidasDepth2import gradio as gr3import numpy as np4import tempfile5 6 7depth_estimator = MidasDepth()8 9 10def get_depth(rgb):11    print("Estimating depth...")12    rgb = rgb.convert("RGB")13    depth = depth_estimator.get_depth(rgb)14 15    print("Creating mesh...")16    w, h = rgb.size17    grid = np.mgrid[0:h, 0:w].transpose(1, 2, 018                                        ).reshape(-1, 2)[..., ::-1]19    flat_grid = grid[:, 1] * w + grid[:, 0]20 21    positions = np.concatenate(((grid - np.array([[w, h]])22                                 / 2) / w * 2,23                                depth.flatten()[flat_grid][..., np.newaxis]),24                               axis=-1)25    positions[:, :-1] *= positions[:, -1:]26    positions[:, :2] *= -127 28    pick_edges = depth < 029    y, x = (t.flatten() for t in np.mgrid[0:h, 0:w])30    faces = np.concatenate((31        np.stack((y * w + x,32                  (y - 1) * w + x,33                  y * w + (x - 1)), axis=-1)34        [(~pick_edges.flatten()) * (x > 0) * (y > 0)],35        np.stack((y * w + x,36                  (y + 1) * w + x,37                  y * w + (x + 1)), axis=-1)38        [(~pick_edges.flatten()) * (x < w - 1) * (y < h - 1)]39    ))40 41    print("Writing...")42    tf = tempfile.NamedTemporaryFile(suffix=".obj").name43    save_obj(positions, np.asarray(rgb).reshape(-1, 3) / 255., faces, tf)44 45    return rgb, (depth.clip(0, 64) * 1024).astype("uint16"), tf46 47 48def save_obj(positions, rgb, faces, filename):49    with open(filename, "w") as f:50        for position, color in zip(positions, rgb):51            f.write(52                f"v {' '.join(map(str, position))} {' '.join(map(str, color))}\n")53        for face in faces:54            f.write(f"f {' '.join(map(str, face))}\n")55 56 57gr.Interface(fn=get_depth, inputs=[58    gr.components.Image(label="rgb", type="pil"),59], outputs=[60    gr.components.Image(type="pil", label="image"),61    gr.components.Image(type="numpy", label="depth"),62    gr.components.Model3D(label="3d model")63 64]).launch(share=True)65