BlurMaster / app.py
ArunLouis's picture
Upload app.py
7fc5388 verified
raw
history blame
2.21 kB
import gradio as gr
import numpy as np
import torch
from PIL import Image
import cv2
import requests
from transformers import pipeline
# Load the depth estimation pipeline
pipe = pipeline(task="depth-estimation", model="depth-anything/Depth-Anything-V2-Small-hf")
def apply_depth_aware_blur(image): # Removed blur parameters
original_image = Image.fromarray(image).convert("RGB")
original_image = original_image.resize((512, 512))
image_np = np.array(original_image)
# Inference
depth = pipe(original_image)["depth"]
depth = np.array(depth) # Convert to numpy array
depth = cv2.resize(depth, (512, 512), interpolation=cv2.INTER_CUBIC) # Resize depth map
# Normalize the depth map
normalized_depth_map = (depth - np.min(depth)) / (np.max(depth) - np.min(depth))
blurred_image = np.copy(np.array(original_image))
# Calculate blur kernel size based on depth
max_kernel_size = 35 # Maximum blur kernel size
for y in range(512):
for x in range(512):
blur_amount = normalized_depth_map[y, x]
kernel_size = int(blur_amount * max_kernel_size)
# Ensure kernel size is odd and at least 1
kernel_size = max(1, kernel_size)
if kernel_size % 2 == 0:
kernel_size += 1
if kernel_size > 1 and kernel_size <= max_kernel_size:
blurred_image[y:y + 1, x:x + 1] = cv2.GaussianBlur(
np.array(original_image)[y:y + 1, x:x + 1], (kernel_size, kernel_size), 10
)
else:
blurred_image[y:y + 1, x:x + 1] = np.array(original_image)[y:y + 1, x:x + 1] #Keep original pixel
return Image.fromarray(blurred_image.astype(np.uint8))
iface = gr.Interface(
fn=apply_depth_aware_blur,
inputs=gr.Image(label="Input Image"),
outputs=gr.Image(label="Blurred Image"),
title="Depth-Proportional Lens Blur App",
description="Apply blur to an image where the blur intensity is proportional to the estimated depth. Farther objects are more blurred, closer objects are sharper.",
)
if __name__ == "__main__":
iface.launch()