nsathya5 commited on
Commit
1ec7e98
·
verified ·
1 Parent(s): e3801a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +221 -163
app.py CHANGED
@@ -3,192 +3,250 @@ import torch
3
  import numpy as np
4
  import cv2
5
  from PIL import Image
6
- from transformers import SegformerForSemanticSegmentation, SegformerFeatureExtractor
7
- from transformers import DPTForDepthEstimation, DPTFeatureExtractor
8
- from scipy.ndimage import gaussian_filter
9
 
10
- # Load segmentation model
11
- segmentation_model_name = "nvidia/segformer-b0-finetuned-ade-512-512"
12
- segmentation_feature_extractor = SegformerFeatureExtractor.from_pretrained(segmentation_model_name)
13
- segmentation_model = SegformerForSemanticSegmentation.from_pretrained(segmentation_model_name)
 
 
 
 
14
 
15
- # Load depth estimation model
16
- depth_model_name = "Intel/dpt-large"
17
- depth_feature_extractor = DPTFeatureExtractor.from_pretrained(depth_model_name)
18
- depth_model = DPTForDepthEstimation.from_pretrained(depth_model_name)
 
 
 
 
19
 
20
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
- segmentation_model.to(device)
22
- depth_model.to(device)
23
 
24
- def apply_segmentation(image):
25
- # Preprocess
26
- inputs = segmentation_feature_extractor(images=image, return_tensors="pt")
27
- inputs = {k: v.to(device) for k, v in inputs.items()}
28
-
29
- # Forward pass
30
- with torch.no_grad():
31
- outputs = segmentation_model(**inputs)
32
- logits = outputs.logits
33
-
34
- # Convert logits to segmentation mask
35
- segmentation_mask = torch.argmax(logits, dim=1)[0].cpu().numpy()
36
-
37
- # Create a binary mask for foreground (assume person class is usually indexed as 15)
38
- # For simplicity, consider everything as foreground (non-zero values)
39
- binary_mask = (segmentation_mask > 0).astype(np.uint8) * 255
40
-
41
- # Resize binary mask to match input image if needed
42
- if binary_mask.shape[:2] != image.size[::-1]:
43
- binary_mask = cv2.resize(binary_mask, image.size[::-1])
44
-
45
- return binary_mask
46
-
47
- def apply_depth_estimation(image):
48
- # Preprocess
49
- inputs = depth_feature_extractor(images=image, return_tensors="pt")
50
- inputs = {k: v.to(device) for k, v in inputs.items()}
51
-
52
- # Forward pass
53
- with torch.no_grad():
54
- outputs = depth_model(**inputs)
55
- predicted_depth = outputs.predicted_depth
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- # Convert to numpy
58
- depth_map = predicted_depth[0].cpu().numpy()
 
 
59
 
60
- # Normalize depth map for visualization
61
- depth_map = (depth_map - depth_map.min()) / (depth_map.max() - depth_map.min())
62
- depth_map = (depth_map * 255).astype(np.uint8)
63
 
64
- # Resize depth map to match input image if needed
65
- if depth_map.shape[:2] != image.size[::-1]:
66
- depth_map = cv2.resize(depth_map, image.size[::-1])
67
 
68
- return depth_map
69
 
70
- def apply_gaussian_blur(image, mask, sigma=15):
71
- # Convert PIL image to numpy array
72
- img_np = np.array(image)
73
-
74
- # Create blurred version of the entire image
75
- blurred = gaussian_filter(img_np, sigma=(sigma, sigma, 0))
76
-
77
- # Make sure mask has the right shape
78
- if len(mask.shape) == 2:
79
- mask = np.expand_dims(mask, -1)
80
- if mask.shape[2] == 1:
81
- mask = np.repeat(mask, 3, axis=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- # Normalize mask to [0, 1]
84
- normalized_mask = mask.astype(float) / 255
 
 
85
 
86
- # Combine original and blurred images based on mask
87
- result = img_np * normalized_mask + blurred * (1 - normalized_mask)
88
- result = result.astype(np.uint8)
89
 
90
- return Image.fromarray(result)
91
 
92
- def apply_depth_blur(image, depth_map, max_sigma=30):
93
- # Convert PIL image to numpy array
94
- img_np = np.array(image)
95
-
96
- # Make sure depth map has the right shape
97
- if len(depth_map.shape) == 3 and depth_map.shape[2] > 1:
98
- depth_map = cv2.cvtColor(depth_map, cv2.COLOR_RGB2GRAY)
99
-
100
- # Create normalized depth map for blur strength calculation
101
- # Invert depth map so that closer objects have smaller sigma values
102
- depth_normalized = 1.0 - (depth_map.astype(float) / 255.0)
103
-
104
- # For each pixel, apply Gaussian blur with varying sigma
105
- height, width = img_np.shape[:2]
106
- result = np.zeros_like(img_np)
107
-
108
- # This is a simplified approach - ideally we'd use a more efficient method
109
- # Create multiple blurred versions of the image with different sigma values
110
- blur_layers = []
111
- sigma_values = np.linspace(1, max_sigma, 10)
112
- for sigma in sigma_values:
113
- blur_layers.append(gaussian_filter(img_np, sigma=(sigma, sigma, 0)))
114
-
115
- # Interpolate between blur layers based on depth
116
- for y in range(height):
117
- for x in range(width):
118
- # Map depth value to index in blur_layers
119
- depth_val = depth_normalized[y, x]
120
- idx = int(depth_val * (len(blur_layers) - 1))
121
- # Ensure valid index
122
- idx = max(0, min(idx, len(blur_layers) - 1))
123
- result[y, x] = blur_layers[idx][y, x]
124
-
125
- return Image.fromarray(result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
- def process_image(input_image, blur_type, blur_intensity):
128
- # Apply segmentation
129
- mask = apply_segmentation(input_image)
130
-
131
- # Apply depth estimation
132
- depth_map = apply_depth_estimation(input_image)
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
- # Create visualization of segmentation mask
141
- mask_visualized = Image.fromarray(mask).convert("RGB")
142
-
143
- # Create visualization of depth map
144
- depth_visualized = Image.fromarray(depth_map).convert("RGB")
145
 
146
- return output_image, mask_visualized, depth_visualized
147
-
148
- # Create the Gradio interface
149
- with gr.Blocks(title="Background Blur Effects") as demo:
150
- gr.Markdown("# Background Blur Effects using Vision Transformers")
151
- gr.Markdown("""
152
- This application demonstrates two types of background blur effects:
153
- 1. **Gaussian Blur**: Simple blur applied to the background using segmentation
154
- 2. **Depth-based Lens Blur**: Realistic lens blur effect based on depth estimation
155
- """)
 
 
 
156
 
157
  with gr.Row():
158
- with gr.Column():
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", type="pil")
176
- depth_map = gr.Image(label="Depth Map", type="pil")
177
 
178
- submit_btn.click(
179
- process_image,
180
- inputs=[input_image, blur_type, blur_intensity],
 
181
  outputs=[output_image, segmentation_mask, depth_map]
182
  )
183
 
184
- gr.Markdown("""
185
- ### How it works
186
- 1. **Segmentation**: Identifies foreground objects using SegFormer
187
- 2. **Depth Estimation**: Generates a depth map using DPT
188
- 3. **Blur Application**: Applies blur effects based on segmentation and depth information
189
-
190
- *Created for EEE 515 Assignment 3*
191
- """)
192
 
193
- # Launch the app
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()