Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from transformers import DPTForDepthEstimation, DPTImageProcessor
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import cv2
|
| 7 |
+
|
| 8 |
+
# Load the model and processor only once (faster performance)
|
| 9 |
+
model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
|
| 10 |
+
processor = DPTImageProcessor.from_pretrained("Intel/dpt-large")
|
| 11 |
+
|
| 12 |
+
def apply_depth_blur(image, max_blur=31, threshold=0.2):
|
| 13 |
+
"""Applies depth-based Gaussian blur using the DPT model."""
|
| 14 |
+
image_np = np.array(image) # Convert to numpy array
|
| 15 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 16 |
+
|
| 17 |
+
with torch.no_grad():
|
| 18 |
+
depth_map = model(**inputs).predicted_depth
|
| 19 |
+
depth_map = torch.nn.functional.interpolate(
|
| 20 |
+
depth_map.unsqueeze(1),
|
| 21 |
+
size=image.size[::-1],
|
| 22 |
+
mode="bicubic",
|
| 23 |
+
align_corners=False,
|
| 24 |
+
).squeeze().cpu().numpy()
|
| 25 |
+
|
| 26 |
+
# Normalize the depth map
|
| 27 |
+
depth_map = (depth_map - depth_map.min()) / (depth_map.max() - depth_map.min())
|
| 28 |
+
depth_map = cv2.GaussianBlur(depth_map, (9, 9), 0)
|
| 29 |
+
|
| 30 |
+
# Apply different blur levels based on depth
|
| 31 |
+
output = image_np.copy()
|
| 32 |
+
unique_blur_values = np.unique((depth_map * max_blur).astype(int) // 2 * 2 + 1)
|
| 33 |
+
|
| 34 |
+
for ksize in unique_blur_values:
|
| 35 |
+
if ksize > 1:
|
| 36 |
+
mask = (depth_map * max_blur).astype(int) == ksize
|
| 37 |
+
output[mask] = cv2.GaussianBlur(image_np, (ksize, ksize), 0)[mask]
|
| 38 |
+
|
| 39 |
+
return output
|
| 40 |
+
|
| 41 |
+
# Gradio UI
|
| 42 |
+
with gr.Blocks() as app:
|
| 43 |
+
gr.Markdown("## 🔥 Depth-Based Gaussian Blur Effect 🔥")
|
| 44 |
+
with gr.Row():
|
| 45 |
+
with gr.Column():
|
| 46 |
+
img_input = gr.Image(label="Upload Image", type="pil")
|
| 47 |
+
max_blur = gr.Slider(1, 101, 31, step=2, label="Max Blur Intensity")
|
| 48 |
+
threshold = gr.Slider(0, 1, 0.2, step=0.1, label="Blur Threshold")
|
| 49 |
+
btn = gr.Button("Apply Blur")
|
| 50 |
+
with gr.Column():
|
| 51 |
+
img_output = gr.Image(label="Blurred Image")
|
| 52 |
+
|
| 53 |
+
btn.click(fn=apply_depth_blur, inputs=[img_input, max_blur, threshold], outputs=img_output)
|
| 54 |
+
|
| 55 |
+
app.launch()
|