File size: 8,682 Bytes
d110ed4
 
e28b51d
 
 
d110ed4
e28b51d
 
 
 
 
d110ed4
e28b51d
 
d110ed4
e28b51d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b7d147
e28b51d
 
 
d110ed4
e28b51d
d110ed4
e28b51d
9b7d147
d110ed4
9b7d147
e28b51d
9b7d147
e28b51d
 
 
 
d110ed4
e28b51d
 
d110ed4
9b7d147
d110ed4
 
 
9b7d147
d110ed4
 
e28b51d
9b7d147
d110ed4
e28b51d
d110ed4
9b7d147
e28b51d
 
246a819
e28b51d
246a819
e28b51d
 
246a819
 
 
 
 
 
 
 
 
 
 
 
 
e28b51d
 
 
d110ed4
e28b51d
 
 
d110ed4
 
e28b51d
 
d110ed4
 
 
e28b51d
 
d110ed4
e28b51d
 
d110ed4
9b7d147
d110ed4
 
 
e18a03c
 
 
d110ed4
246a819
 
 
d110ed4
9b7d147
e28b51d
 
 
d110ed4
9b7d147
e28b51d
 
 
 
246a819
e28b51d
 
 
d110ed4
 
e28b51d
 
9b7d147
e28b51d
 
 
 
 
d110ed4
e28b51d
 
 
246a819
d110ed4
e28b51d
 
 
 
 
246a819
 
 
e28b51d
9b7d147
246a819
 
 
e28b51d
 
 
 
 
 
 
 
 
 
d110ed4
246a819
d110ed4
e28b51d
 
 
246a819
d110ed4
 
8d977b7
e28b51d
246a819
 
e2980eb
 
246a819
e28b51d
 
 
 
 
 
 
 
 
d110ed4
 
 
 
 
e28b51d
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import cv2
import numpy as np
from PIL import Image, ImageFilter
import torch
import gradio as gr
from torchvision import transforms
from transformers import (
    AutoModelForImageSegmentation,
    DepthProImageProcessorFast,
    DepthProForDepthEstimation,
)

# Set device
device = "cuda" if torch.cuda.is_available() else "cpu"

# -----------------------------
# Load Segmentation Model (RMBG-2.0 by briaai)
# -----------------------------
seg_model = AutoModelForImageSegmentation.from_pretrained(
    "briaai/RMBG-2.0", trust_remote_code=True
)
torch.set_float32_matmul_precision(["high", "highest"][0])
seg_model.to(device)
seg_model.eval()

# Define segmentation image size and transform
seg_image_size = (1024, 1024)
seg_transform = transforms.Compose([
    transforms.Resize(seg_image_size),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

# -----------------------------
# Load Depth Estimation Model (DepthPro by Apple)
# -----------------------------
depth_processor = DepthProImageProcessorFast.from_pretrained("apple/DepthPro-hf")
depth_model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf")
depth_model.to(device)
depth_model.eval()

# -----------------------------
# Define the Segmentation-Based Blur Effect
# -----------------------------
def segmentation_blur_effect(input_image: Image.Image):
    """
    Creates a segmentation mask using RMBG-2.0 and applies a Gaussian blur (sigma=15)
    to the background while keeping the foreground sharp.
    """
    # Resize input image for segmentation processing
    imageResized = input_image.resize(seg_image_size)
    input_tensor = seg_transform(imageResized).unsqueeze(0).to(device)
    
    with torch.no_grad():
        preds = seg_model(input_tensor)[-1].sigmoid().cpu()
    pred = preds[0].squeeze()
    
    # Convert predicted mask to a PIL image and ensure it matches imageResized's size
    pred_pil = transforms.ToPILImage()(pred)
    mask = pred_pil.resize(imageResized.size)
    
    # Convert mask to grayscale and threshold to create a binary mask
    mask_np = np.array(mask.convert("L"))
    _, maskBinary = cv2.threshold(mask_np, 127, 255, cv2.THRESH_BINARY)
    
    # Convert the resized image to an OpenCV BGR array
    img = cv2.cvtColor(np.array(imageResized), cv2.COLOR_RGB2BGR)
    # Apply Gaussian blur (sigmaX=15, sigmaY=15)
    blurredBg = cv2.GaussianBlur(np.array(imageResized), (0, 0), sigmaX=15, sigmaY=15)
    
    # Create the inverse mask and convert it to 3 channels
    maskInv = cv2.bitwise_not(maskBinary)
    maskInv3 = cv2.cvtColor(maskInv, cv2.COLOR_GRAY2BGR)
    
    # Extract the foreground and background using the mask
    foreground = cv2.bitwise_and(img, cv2.bitwise_not(maskInv3))
    background = cv2.bitwise_and(blurredBg, maskInv3)
    
    # Combine foreground and background; convert back to RGB for display
    finalImg = cv2.add(cv2.cvtColor(foreground, cv2.COLOR_BGR2RGB), background)
    finalImg_pil = Image.fromarray(finalImg)
    
    return finalImg_pil, mask

# -----------------------------
# Define the Depth-Based Lens Blur Effect with Slider-Controlled Thresholds
# -----------------------------
def lens_blur_effect(input_image: Image.Image, fg_threshold: float = 85, mg_threshold: float = 170):
    """
    Uses DepthPro to estimate a depth map and applies a dynamic lens blur effect
    by blending three versions of the image with increasing blur levels.
    
    Parameters:
      input_image: The original PIL image.
      fg_threshold: Foreground threshold (0-255). Pixels with depth below this are considered foreground.
      mg_threshold: Middleground threshold (0-255). Pixels with depth between fg_threshold and mg_threshold are middleground.
    
    Returns:
      depthImg: The computed depth map (PIL Image).
      lensBlurImage: The final lens-blurred image (PIL Image).
      mask_fg_img: Foreground depth mask.
      mask_mg_img: Middleground depth mask.
      mask_bg_img: Background depth mask.
    """
    # Process the image with the depth estimation model
    inputs = depth_processor(images=input_image, return_tensors="pt").to(device)
    with torch.no_grad():
        outputs = depth_model(**inputs)
    post_processed_output = depth_processor.post_process_depth_estimation(
        outputs, target_sizes=[(input_image.height, input_image.width)]
    )
    depth = post_processed_output[0]["predicted_depth"]
    
    # Normalize depth to [0, 255]
    depth = (depth - depth.min()) / (depth.max() - depth.min())
    depth = depth * 255.
    depth = depth.detach().cpu().numpy()
    depth_map = depth.astype(np.uint8)
    depthImg = Image.fromarray(depth_map)
    
    # Convert input image to OpenCV BGR format
    img = cv2.cvtColor(np.array(input_image), cv2.COLOR_RGB2BGR)
    
    # Precompute blurred versions for different depth regions
    img_foreground = img.copy()  # No blur for foreground
    img_middleground = cv2.GaussianBlur(img, (0, 0), sigmaX=7, sigmaY=7)
    img_background = cv2.GaussianBlur(img, (0, 0), sigmaX=15, sigmaY=15)

    print(depth_map)
    depth_map /= depth_map.max()
    
    # Use slider values as thresholds
    threshold1 = fg_threshold   # e.g., default 85
    threshold2 = mg_threshold   # e.g., default 170
    
    # Create masks for foreground, middleground, and background based on depth
    mask_fg = (depth_map < threshold1).astype(np.float32)
    mask_mg = ((depth_map >= threshold1) & (depth_map < threshold2)).astype(np.float32)
    mask_bg = (depth_map >= threshold2).astype(np.float32)
    
    # Expand masks to 3 channels
    mask_fg_3 = np.stack([mask_fg]*3, axis=-1)
    mask_mg_3 = np.stack([mask_mg]*3, axis=-1)
    mask_bg_3 = np.stack([mask_bg]*3, axis=-1)
    
    # Blend the images using the masks
    final_img = (img_foreground * mask_fg_3 +
                 img_middleground * mask_mg_3 +
                 img_background * mask_bg_3).astype(np.uint8)
    
    final_img_rgb = cv2.cvtColor(final_img, cv2.COLOR_BGR2RGB)
    lensBlurImage = Image.fromarray(final_img_rgb)
    
    # Create mask images for display (scaled to 0-255)
    mask_fg_img = Image.fromarray((mask_fg * 255).astype(np.uint8))
    mask_mg_img = Image.fromarray((mask_mg * 255).astype(np.uint8))
    mask_bg_img = Image.fromarray((mask_bg * 255).astype(np.uint8))
    
    return depthImg, lensBlurImage, mask_fg_img, mask_mg_img, mask_bg_img

# -----------------------------
# Gradio App: Process Image and Display Multiple Effects
# -----------------------------
def process_image(input_image: Image.Image, fg_threshold: float, mg_threshold: float):
    """
    Processes the uploaded image to generate:
      1. Segmentation-based Gaussian blur effect.
      2. Segmentation mask.
      3. Depth map.
      4. Depth-based lens blur effect.
      5. Depth masks for foreground, middleground, and background.
    
    The depth thresholds for foreground and middleground regions are adjustable via sliders.
    """
    seg_blur, seg_mask = segmentation_blur_effect(input_image)
    depth_map_img, lens_blur_img, mask_fg_img, mask_mg_img, mask_bg_img = lens_blur_effect(
        input_image, fg_threshold, mg_threshold
    )
    
    return (
        seg_blur,
        seg_mask,
        depth_map_img,
        lens_blur_img,
        mask_fg_img,
        mask_mg_img,
        mask_bg_img
    )

title = "Blur Effects: Gaussian & Depth-Based Lens Blur with Adjustable Depth Thresholds"
description = (
    "Upload an image to apply two distinct effects:\n\n"
    "1. A segmentation-based Gaussian blur that blurs the background (using RMBG-2.0).\n"
    "2. A depth-based lens blur effect that simulates realistic lens blur based on depth (using DepthPro).\n\n"
    "Use the sliders to adjust the foreground and middleground depth thresholds."
)

demo = gr.Interface(
    fn=process_image,
    inputs=[
        gr.Image(type="pil", label="Input Image"),
        gr.Slider(minimum=0, maximum=1, step=0.01, value=0.33, label="Foreground Depth Threshold"),
        gr.Slider(minimum=0, maximum=1, step=0.01, value=0.66, label="Middleground Depth Threshold")
    ],
    outputs=[
        gr.Image(type="pil", label="Segmentation-Based Blur"),
        gr.Image(type="pil", label="Segmentation Mask"),
        gr.Image(type="pil", label="Depth Map"),
        gr.Image(type="pil", label="Depth-Based Lens Blur"),
        gr.Image(type="pil", label="Foreground Depth Mask"),
        gr.Image(type="pil", label="Middleground Depth Mask"),
        gr.Image(type="pil", label="Background Depth Mask")
    ],
    title=title,
    description=description,
    allow_flagging="never"
)

if __name__ == "__main__":
    demo.launch()