Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,192 +3,250 @@ import torch
|
|
3 |
import numpy as np
|
4 |
import cv2
|
5 |
from PIL import Image
|
6 |
-
|
7 |
-
from transformers import
|
8 |
-
from
|
9 |
|
10 |
-
# Load segmentation model
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
14 |
|
15 |
-
# Load depth estimation model
|
16 |
-
|
17 |
-
|
18 |
-
depth_model = DPTForDepthEstimation.from_pretrained(
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
|
24 |
-
def
|
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 |
-
depth_map = (depth_map * 255).astype(np.uint8)
|
63 |
|
64 |
-
#
|
65 |
-
|
66 |
-
|
67 |
|
68 |
-
return
|
69 |
|
70 |
-
def
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
-
#
|
84 |
-
|
|
|
|
|
85 |
|
86 |
-
#
|
87 |
-
|
88 |
-
|
89 |
|
90 |
-
return
|
91 |
|
92 |
-
def
|
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 |
-
# Apply appropriate blur effect
|
135 |
-
if blur_type == "Gaussian Blur":
|
136 |
-
output_image = apply_gaussian_blur(input_image, mask, sigma=blur_intensity)
|
137 |
-
else: # "Depth-based Lens Blur"
|
138 |
-
output_image = apply_depth_blur(input_image, depth_map, max_sigma=blur_intensity)
|
139 |
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
# Create visualization of depth map
|
144 |
-
depth_visualized = Image.fromarray(depth_map).convert("RGB")
|
145 |
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
|
|
|
|
|
|
156 |
|
157 |
with gr.Row():
|
158 |
-
|
159 |
-
input_image = gr.Image(label="Input Image", type="pil")
|
160 |
-
blur_type = gr.Radio(
|
161 |
-
["Gaussian Blur", "Depth-based Lens Blur"],
|
162 |
-
label="Blur Effect Type",
|
163 |
-
value="Gaussian Blur"
|
164 |
-
)
|
165 |
-
blur_intensity = gr.Slider(
|
166 |
-
minimum=1, maximum=30, value=15,
|
167 |
-
label="Blur Intensity", step=1
|
168 |
-
)
|
169 |
-
submit_btn = gr.Button("Apply Effect")
|
170 |
-
|
171 |
-
with gr.Column():
|
172 |
-
output_image = gr.Image(label="Output Image", type="pil")
|
173 |
|
174 |
with gr.Row():
|
175 |
-
segmentation_mask = gr.Image(label="Segmentation Mask"
|
176 |
-
depth_map = gr.Image(label="Depth Map"
|
177 |
|
178 |
-
|
179 |
-
|
180 |
-
|
|
|
181 |
outputs=[output_image, segmentation_mask, depth_map]
|
182 |
)
|
183 |
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
*Created for EEE 515 Assignment 3*
|
191 |
-
""")
|
192 |
|
193 |
-
# Launch the
|
194 |
demo.launch()
|
|
|
3 |
import numpy as np
|
4 |
import cv2
|
5 |
from PIL import Image
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
from transformers import AutoFeatureExtractor, SegformerForSemanticSegmentation
|
8 |
+
from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
9 |
|
10 |
+
# Load a smaller segmentation model
|
11 |
+
try:
|
12 |
+
seg_processor = AutoFeatureExtractor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
|
13 |
+
seg_model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
|
14 |
+
print("✓ Segmentation model loaded successfully")
|
15 |
+
except Exception as e:
|
16 |
+
print(f"! Error loading segmentation model: {e}")
|
17 |
+
# Fallback implementation will be used
|
18 |
|
19 |
+
# Load a smaller depth estimation model
|
20 |
+
try:
|
21 |
+
depth_processor = DPTFeatureExtractor.from_pretrained("Intel/dpt-hybrid-midas")
|
22 |
+
depth_model = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas")
|
23 |
+
print("✓ Depth model loaded successfully")
|
24 |
+
except Exception as e:
|
25 |
+
print(f"! Error loading depth model: {e}")
|
26 |
+
# Fallback implementation will be used
|
27 |
|
28 |
+
def apply_gaussian_blur(image, sigma=15):
|
29 |
+
"""Apply Gaussian blur with specified sigma value."""
|
30 |
+
return cv2.GaussianBlur(image, (0, 0), sigma)
|
31 |
|
32 |
+
def get_foreground_mask(image):
|
33 |
+
"""Get foreground mask through simple methods if model fails."""
|
34 |
+
try:
|
35 |
+
# Try using the model first
|
36 |
+
if seg_model is not None and seg_processor is not None:
|
37 |
+
# Convert to RGB if needed
|
38 |
+
if isinstance(image, np.ndarray):
|
39 |
+
if len(image.shape) == 2:
|
40 |
+
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
|
41 |
+
elif image.shape[2] == 4:
|
42 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
|
43 |
+
pil_image = Image.fromarray(image)
|
44 |
+
else:
|
45 |
+
pil_image = image.convert('RGB')
|
46 |
+
|
47 |
+
# Prepare image for the model
|
48 |
+
inputs = seg_processor(images=pil_image, return_tensors="pt")
|
49 |
+
|
50 |
+
# Run inference
|
51 |
+
with torch.no_grad():
|
52 |
+
outputs = seg_model(**inputs)
|
53 |
+
|
54 |
+
# Process logits
|
55 |
+
logits = outputs.logits
|
56 |
+
upsampled_logits = torch.nn.functional.interpolate(
|
57 |
+
logits,
|
58 |
+
size=(image.shape[0], image.shape[1]),
|
59 |
+
mode="bilinear",
|
60 |
+
align_corners=False,
|
61 |
+
)
|
62 |
+
|
63 |
+
# Get mask (consider classes that are typically foreground, e.g., person)
|
64 |
+
# In ADE20K dataset, person is class 12
|
65 |
+
pred_seg = upsampled_logits.argmax(dim=1)[0]
|
66 |
+
mask = (pred_seg == 12).float().cpu().numpy() # Person class
|
67 |
+
|
68 |
+
# If person isn't detected, try other common foreground classes
|
69 |
+
if mask.sum() < 100: # If almost no pixels were classified as person
|
70 |
+
for cls in [13, 14, 15]: # Try other classes like vehicle, animal, etc.
|
71 |
+
cls_mask = (pred_seg == cls).float().cpu().numpy()
|
72 |
+
if cls_mask.sum() > mask.sum():
|
73 |
+
mask = cls_mask
|
74 |
+
|
75 |
+
return mask
|
76 |
+
|
77 |
+
except Exception as e:
|
78 |
+
print(f"Error in segmentation: {e}")
|
79 |
|
80 |
+
# Fallback: Use a simple method - assume center of image is foreground
|
81 |
+
h, w = image.shape[:2]
|
82 |
+
y, x = np.ogrid[:h, :w]
|
83 |
+
center_y, center_x = h / 2, w / 2
|
84 |
|
85 |
+
# Create a circular mask (foreground is in center)
|
86 |
+
mask = ((x - center_x)**2 / (w/3)**2 + (y - center_y)**2 / (h/3)**2) <= 1
|
|
|
87 |
|
88 |
+
# Convert to float and smooth edges
|
89 |
+
mask = mask.astype(np.float32)
|
90 |
+
mask = cv2.GaussianBlur(mask, (51, 51), 30)
|
91 |
|
92 |
+
return mask
|
93 |
|
94 |
+
def get_depth_map(image):
|
95 |
+
"""Get depth map from the image using model or fallback."""
|
96 |
+
try:
|
97 |
+
# Try using the model first
|
98 |
+
if depth_model is not None and depth_processor is not None:
|
99 |
+
# Convert to RGB if needed
|
100 |
+
if isinstance(image, np.ndarray):
|
101 |
+
if len(image.shape) == 2:
|
102 |
+
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
|
103 |
+
elif image.shape[2] == 4:
|
104 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
|
105 |
+
pil_image = Image.fromarray(image)
|
106 |
+
else:
|
107 |
+
pil_image = image.convert('RGB')
|
108 |
+
|
109 |
+
# Prepare image for the model
|
110 |
+
inputs = depth_processor(images=pil_image, return_tensors="pt")
|
111 |
+
|
112 |
+
# Run inference
|
113 |
+
with torch.no_grad():
|
114 |
+
outputs = depth_model(**inputs)
|
115 |
+
|
116 |
+
predicted_depth = outputs.predicted_depth
|
117 |
+
|
118 |
+
# Interpolate to original size if needed
|
119 |
+
depth_map = torch.nn.functional.interpolate(
|
120 |
+
predicted_depth.unsqueeze(1),
|
121 |
+
size=(image.shape[0], image.shape[1]),
|
122 |
+
mode="bicubic",
|
123 |
+
align_corners=False,
|
124 |
+
).squeeze().cpu().numpy()
|
125 |
+
|
126 |
+
return depth_map
|
127 |
+
|
128 |
+
except Exception as e:
|
129 |
+
print(f"Error in depth estimation: {e}")
|
130 |
|
131 |
+
# Fallback: Create a simple depth map based on distance from center
|
132 |
+
h, w = image.shape[:2]
|
133 |
+
y, x = np.ogrid[:h, :w]
|
134 |
+
center_y, center_x = h / 2, w / 2
|
135 |
|
136 |
+
# Create a radial gradient (closer to center = closer distance)
|
137 |
+
depth = ((x - center_x)**2 / (w/2)**2 + (y - center_y)**2 / (h/2)**2)
|
138 |
+
depth = np.clip(depth, 0, 1)
|
139 |
|
140 |
+
return depth
|
141 |
|
142 |
+
def process_image(input_image, blur_type="gaussian", blur_sigma=15):
|
143 |
+
"""Process the input image and return the results."""
|
144 |
+
try:
|
145 |
+
# Convert from Gradio format
|
146 |
+
img = np.array(input_image)
|
147 |
+
if img.ndim == 2: # Grayscale
|
148 |
+
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
|
149 |
+
elif img.shape[2] == 4: # RGBA
|
150 |
+
img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
|
151 |
+
|
152 |
+
# 1. Get segmentation mask
|
153 |
+
mask = get_foreground_mask(img)
|
154 |
+
mask_vis = (mask * 255).astype(np.uint8)
|
155 |
+
mask_color = cv2.applyColorMap(mask_vis, cv2.COLORMAP_JET)
|
156 |
+
|
157 |
+
# 2. Get depth map
|
158 |
+
depth_map = get_depth_map(img)
|
159 |
+
depth_norm = (depth_map - depth_map.min()) / (depth_map.max() - depth_map.min() + 1e-8)
|
160 |
+
depth_vis = plt.cm.viridis(depth_norm)[:, :, :3]
|
161 |
+
depth_vis = (depth_vis * 255).astype(np.uint8)
|
162 |
+
|
163 |
+
# Apply appropriate blur effect
|
164 |
+
if blur_type == "gaussian":
|
165 |
+
# Apply regular Gaussian blur
|
166 |
+
blurred_img = apply_gaussian_blur(img, sigma=blur_sigma)
|
167 |
+
|
168 |
+
# Combine original foreground with blurred background
|
169 |
+
result = img.copy()
|
170 |
+
for c in range(3): # For each color channel
|
171 |
+
result[:,:,c] = mask * img[:,:,c] + (1-mask) * blurred_img[:,:,c]
|
172 |
+
|
173 |
+
else: # depth-based blur
|
174 |
+
# Apply depth-based blur
|
175 |
+
result = img.copy()
|
176 |
+
|
177 |
+
# Apply varying levels of blur based on depth
|
178 |
+
# For simplicity, we'll use 5 levels of blur
|
179 |
+
for i in range(1, 6):
|
180 |
+
sigma = blur_sigma * i / 5 # Increasing sigma value
|
181 |
+
level_blurred = apply_gaussian_blur(img, sigma=sigma)
|
182 |
+
|
183 |
+
# Calculate weight for this blur level
|
184 |
+
weight = (depth_norm > (i-1)/5) & (depth_norm <= i/5)
|
185 |
+
weight = weight.astype(np.float32)
|
186 |
+
|
187 |
+
# Apply this blur level where applicable
|
188 |
+
for c in range(3):
|
189 |
+
result[:,:,c] = np.where(weight, level_blurred[:,:,c], result[:,:,c])
|
190 |
+
|
191 |
+
# Convert to uint8
|
192 |
+
result = result.astype(np.uint8)
|
193 |
+
|
194 |
+
return result, mask_color, depth_vis
|
195 |
+
|
196 |
+
except Exception as e:
|
197 |
+
print(f"Error processing image: {e}")
|
198 |
+
# Return original image if processing fails
|
199 |
+
if isinstance(input_image, np.ndarray):
|
200 |
+
return input_image, input_image, input_image
|
201 |
+
else:
|
202 |
+
img = np.array(input_image)
|
203 |
+
return img, img, img
|
204 |
|
205 |
+
# Create Gradio interface
|
206 |
+
with gr.Blocks(title="Image Blur Effects") as demo:
|
207 |
+
gr.Markdown("# Image Blur Effects App")
|
208 |
+
gr.Markdown("Upload an image to apply two types of blur effects:")
|
209 |
+
gr.Markdown("1. **Gaussian Blur**: Blurs the background while keeping the foreground sharp")
|
210 |
+
gr.Markdown("2. **Depth-based Lens Blur**: Applies varying blur intensities based on estimated depth")
|
|
|
|
|
|
|
|
|
|
|
|
|
211 |
|
212 |
+
with gr.Row():
|
213 |
+
input_image = gr.Image(label="Input Image", type="numpy")
|
214 |
+
output_image = gr.Image(label="Output Image")
|
|
|
|
|
215 |
|
216 |
+
with gr.Row():
|
217 |
+
blur_effect_type = gr.Radio(
|
218 |
+
["Gaussian Blur", "Depth-based Lens Blur"],
|
219 |
+
label="Blur Effect Type",
|
220 |
+
value="Gaussian Blur"
|
221 |
+
)
|
222 |
+
blur_intensity = gr.Slider(
|
223 |
+
minimum=1,
|
224 |
+
maximum=30,
|
225 |
+
value=15,
|
226 |
+
step=1,
|
227 |
+
label="Blur Intensity"
|
228 |
+
)
|
229 |
|
230 |
with gr.Row():
|
231 |
+
apply_button = gr.Button("Apply Effect")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
|
233 |
with gr.Row():
|
234 |
+
segmentation_mask = gr.Image(label="Segmentation Mask")
|
235 |
+
depth_map = gr.Image(label="Depth Map")
|
236 |
|
237 |
+
# Set up the click event
|
238 |
+
apply_button.click(
|
239 |
+
process_image,
|
240 |
+
inputs=[input_image, blur_effect_type, blur_intensity],
|
241 |
outputs=[output_image, segmentation_mask, depth_map]
|
242 |
)
|
243 |
|
244 |
+
# Examples section
|
245 |
+
gr.Markdown("## How to use")
|
246 |
+
gr.Markdown("1. Upload your image")
|
247 |
+
gr.Markdown("2. Select blur type (Gaussian or Depth-based)")
|
248 |
+
gr.Markdown("3. Adjust blur intensity")
|
249 |
+
gr.Markdown("4. Click 'Apply Effect'")
|
|
|
|
|
250 |
|
251 |
+
# Launch the demo
|
252 |
demo.launch()
|