CoolFace
Apppublic

adpro/dpt-depth01

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py92 linesDownload Raw Back to root
1from doctest import Example2import gradio as gr3from transformers import DPTImageProcessor, DPTForDepthEstimation4import torch5import numpy as np6from PIL import Image, ImageOps7from pathlib import Path8import glob9from autostereogram.converter import StereogramConverter10from datetime import datetime11import time12import tempfile13 14feature_extractor = DPTImageProcessor.from_pretrained("Intel/dpt-large")15model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")16 17stereo_converter = StereogramConverter()18 19 20def process_image(image_path):21    print("\n\n\n")22    print("Processing image:", image_path)23    last_time = time.time()24    image_raw = Image.open(Path(image_path))25 26    image = image_raw27 28    # prepare image for the model29    encoding = feature_extractor(image, return_tensors="pt")30 31    # forward pass32    with torch.no_grad():33        outputs = model(**encoding)34        predicted_depth = outputs.predicted_depth35 36    # interpolate to original size37    prediction = torch.nn.functional.interpolate(38        predicted_depth.unsqueeze(1),39        size=image.size[::-1],40        mode="bicubic",41        align_corners=False,42    ).squeeze()43    output = prediction.cpu().numpy()44    depth_image = (output * 255 / np.max(output)).astype("uint8")45    depth_image_padded = np.array(46      Image.fromarray(depth_image)47    )48 49 50    # Return as downloadable file51    return depth_image_padded52 53 54 55examples_images = [[f] for f in sorted(glob.glob("examples/*.jpg"))]56 57 58with gr.Blocks() as blocks:59    gr.Markdown(60        """61## Depth Image to Autostereogram (Magic Eye)62This demo is a variation from the original [DPT Demo](https://huggingface.co/spaces/nielsr/dpt-depth-estimation).63Zero-shot depth estimation from an image, then it uses [pystereogram](https://github.com/yxiao1996/pystereogram)64to generate the autostereogram (Magic Eye)65<base target="_blank">66"""67    )68    with gr.Row():69        with gr.Column():70            input_image = gr.Image(type="filepath", label="Input Image")71            button = gr.Button("Predict")72        with gr.Column():73            predicted_depth = gr.Image(label="Predicted Depth", type="pil")74    with gr.Row():75        autostereogram = gr.Image(label="Autostereogram", type="pil")76    with gr.Row():77        with gr.Column():78            file_download = gr.File(label="Download Image")79    with gr.Row():80        gr.Examples(81            examples=examples_images,82            fn=process_image,83            inputs=[input_image],84            outputs=predicted_depth,85            cache_examples=True,86        )87    button.click(88        fn=process_image,89        inputs=[input_image],90        outputs=predicted_depth,91    )92blocks.launch(debug=True)