Candle commited on
Commit
38084f6
·
1 Parent(s): 07ef396
Files changed (1) hide show
  1. correct_fgr.py +90 -13
correct_fgr.py CHANGED
@@ -14,7 +14,8 @@ The foreground correction process:
14
  4. Invert selection to create a mask
15
  5. Apply minimum filter with 4px radius to the RGB image using the inverted selection mask
16
  (equivalent to Filter > Other > Minimum in Photoshop)
17
- 6. Export both versions:
 
18
  - FGR: RGB image with the processed regions
19
  - Masked: RGBA image using the contracted alpha (before inversion) as the alpha channel
20
  """
@@ -78,7 +79,70 @@ def apply_minimum_filter_to_rgb(rgb_image, mask, radius=4):
78
  return filtered_rgb
79
 
80
 
81
- def process_foreground_correction(expanded_path, automatte_path, fgr_output_path, masked_output_path):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  """
83
  Process a single image pair for foreground correction.
84
 
@@ -87,6 +151,10 @@ def process_foreground_correction(expanded_path, automatte_path, fgr_output_path
87
  automatte_path: Path to the automatte (alpha) image
88
  fgr_output_path: Path where the processed RGB image will be saved
89
  masked_output_path: Path where the masked RGBA image will be saved
 
 
 
 
90
  """
91
  # Load the expanded image (RGB)
92
  expanded_img = cv2.imread(expanded_path, cv2.IMREAD_COLOR)
@@ -109,18 +177,21 @@ def process_foreground_correction(expanded_path, automatte_path, fgr_output_path
109
  # Step 1: Alpha channel is already loaded from automatte
110
  alpha = automatte_img.copy()
111
 
112
- # Step 2: Apply thresholding (white = anything >235, black otherwise)
113
- thresholded_alpha = apply_threshold(alpha, threshold=235)
114
 
115
- # Step 3: Contract the alpha channel 1px
116
- contracted_alpha = contract_alpha(thresholded_alpha, pixels=1)
117
- # contracted_alpha = thresholded_alpha
118
 
119
  # Step 4: Invert selection
120
  selection_mask = invert_selection(contracted_alpha)
121
 
122
  # Step 5: Apply minimum filter to RGB image using the selection mask
123
- filtered_rgb = apply_minimum_filter_to_rgb(expanded_img, selection_mask, radius=2)
 
 
 
 
124
 
125
  # # DO NOT COMMIT: save alpha and exit
126
  # cv2.imwrite("debug_expanded.png", expanded_img)
@@ -132,17 +203,17 @@ def process_foreground_correction(expanded_path, automatte_path, fgr_output_path
132
  # cv2.imwrite("debug_filtered_rgb.png", filtered_rgb)
133
  # import sys; sys.exit(0)
134
 
135
- # Apply the original contracted alpha (before inversion) to the filtered RGB image
136
  # Convert to RGBA for masked output
137
- masked_rgba = cv2.cvtColor(filtered_rgb, cv2.COLOR_BGR2BGRA)
138
- masked_rgba[:, :, 3] = alpha # Use the contracted alpha (before inversion)
139
 
140
  # Create output directories if they don't exist
141
  os.makedirs(os.path.dirname(fgr_output_path), exist_ok=True)
142
  os.makedirs(os.path.dirname(masked_output_path), exist_ok=True)
143
 
144
  # Save the processed RGB image (without alpha)
145
- success_fgr = cv2.imwrite(fgr_output_path, filtered_rgb)
146
  if not success_fgr:
147
  print(f"Error: Could not save RGB image to {fgr_output_path}")
148
  return False
@@ -198,6 +269,8 @@ def main():
198
  help="Number of pixels to contract alpha channel (default: 1)")
199
  parser.add_argument("--minimum-radius", type=int, default=4,
200
  help="Radius for minimum filter operation (default: 4)")
 
 
201
  parser.add_argument("--sample", type=str, default=None,
202
  help="Process only specific sample (e.g., 'sample-000')")
203
 
@@ -228,7 +301,11 @@ def main():
228
  for i, (expanded_path, automatte_path, fgr_output_path, masked_output_path) in enumerate(pairs):
229
  print(f"Processing {i+1}/{len(pairs)}: {os.path.basename(fgr_output_path)}")
230
 
231
- if process_foreground_correction(expanded_path, automatte_path, fgr_output_path, masked_output_path):
 
 
 
 
232
  successful += 1
233
  else:
234
  failed += 1
 
14
  4. Invert selection to create a mask
15
  5. Apply minimum filter with 4px radius to the RGB image using the inverted selection mask
16
  (equivalent to Filter > Other > Minimum in Photoshop)
17
+ 6. Apply Gaussian blur on ±0.5 pixel region of selection mask boundaries for smooth transitions
18
+ 7. Export both versions:
19
  - FGR: RGB image with the processed regions
20
  - Masked: RGBA image using the contracted alpha (before inversion) as the alpha channel
21
  """
 
79
  return filtered_rgb
80
 
81
 
82
+ def create_boundary_mask(mask, boundary_width=1):
83
+ """
84
+ Create a boundary mask that covers the edge region of the given mask.
85
+
86
+ Args:
87
+ mask: Binary mask (0 or 255)
88
+ boundary_width: Width of the boundary region in pixels (default: 1 for ±0.5 pixels)
89
+
90
+ Returns:
91
+ Boundary mask where boundaries are white (255)
92
+ """
93
+ # Create kernels for dilation and erosion
94
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*boundary_width+1, 2*boundary_width+1))
95
+
96
+ # Dilate and erode the mask to find boundaries
97
+ dilated = cv2.dilate(mask, kernel, iterations=1)
98
+ eroded = cv2.erode(mask, kernel, iterations=1)
99
+
100
+ # Boundary is the difference between dilated and eroded versions
101
+ boundary = cv2.subtract(dilated, eroded)
102
+
103
+ return boundary
104
+
105
+
106
+ def apply_boundary_blur(rgb_image, boundary_mask, blur_sigma=0.5):
107
+ """
108
+ Apply Gaussian blur to the RGB image only in the boundary regions.
109
+
110
+ Args:
111
+ rgb_image: Input RGB image
112
+ boundary_mask: Binary mask indicating boundary regions
113
+ blur_sigma: Gaussian blur sigma value
114
+
115
+ Returns:
116
+ RGB image with blurred boundaries
117
+ """
118
+ # Convert sigma to kernel size (OpenCV uses kernel size, not sigma directly)
119
+ # Rule of thumb: kernel_size = 2 * int(3 * sigma) + 1
120
+ kernel_size = 2 * int(3 * blur_sigma) + 1
121
+ if kernel_size < 3:
122
+ kernel_size = 3
123
+
124
+ # Make sure kernel size is odd
125
+ if kernel_size % 2 == 0:
126
+ kernel_size += 1
127
+
128
+ # Apply Gaussian blur to the entire image
129
+ blurred_rgb = cv2.GaussianBlur(rgb_image, (kernel_size, kernel_size), blur_sigma)
130
+
131
+ # Create a normalized boundary mask (0.0 to 1.0)
132
+ boundary_mask_norm = (boundary_mask > 0).astype(np.float32)
133
+
134
+ # Blend the original and blurred images based on the boundary mask
135
+ result = rgb_image.copy().astype(np.float32)
136
+
137
+ for channel in range(3):
138
+ result[:, :, channel] = (1.0 - boundary_mask_norm) * rgb_image[:, :, channel].astype(np.float32) + \
139
+ boundary_mask_norm * blurred_rgb[:, :, channel].astype(np.float32)
140
+
141
+ return result.astype(np.uint8)
142
+
143
+
144
+ def process_foreground_correction(expanded_path, automatte_path, fgr_output_path, masked_output_path,
145
+ threshold=253, contract_pixels=1, minimum_radius=4, blur_sigma=0.5):
146
  """
147
  Process a single image pair for foreground correction.
148
 
 
151
  automatte_path: Path to the automatte (alpha) image
152
  fgr_output_path: Path where the processed RGB image will be saved
153
  masked_output_path: Path where the masked RGBA image will be saved
154
+ threshold: Threshold value for alpha binarization
155
+ contract_pixels: Number of pixels to contract alpha channel
156
+ minimum_radius: Radius for minimum filter operation
157
+ blur_sigma: Gaussian blur sigma for boundary smoothing
158
  """
159
  # Load the expanded image (RGB)
160
  expanded_img = cv2.imread(expanded_path, cv2.IMREAD_COLOR)
 
177
  # Step 1: Alpha channel is already loaded from automatte
178
  alpha = automatte_img.copy()
179
 
180
+ # Step 2: Apply thresholding (white = anything >threshold, black otherwise)
181
+ thresholded_alpha = apply_threshold(alpha, threshold=threshold)
182
 
183
+ # Step 3: Contract the alpha channel
184
+ contracted_alpha = contract_alpha(thresholded_alpha, pixels=contract_pixels)
 
185
 
186
  # Step 4: Invert selection
187
  selection_mask = invert_selection(contracted_alpha)
188
 
189
  # Step 5: Apply minimum filter to RGB image using the selection mask
190
+ filtered_rgb = apply_minimum_filter_to_rgb(expanded_img, selection_mask, radius=minimum_radius)
191
+
192
+ # Step 6: Apply Gaussian blur on ±0.5 region of selection mask boundaries
193
+ boundary_mask = create_boundary_mask(selection_mask, boundary_width=1)
194
+ final_rgb = apply_boundary_blur(filtered_rgb, boundary_mask, blur_sigma=blur_sigma)
195
 
196
  # # DO NOT COMMIT: save alpha and exit
197
  # cv2.imwrite("debug_expanded.png", expanded_img)
 
203
  # cv2.imwrite("debug_filtered_rgb.png", filtered_rgb)
204
  # import sys; sys.exit(0)
205
 
206
+ # Apply the original contracted alpha (before inversion) to the final RGB image
207
  # Convert to RGBA for masked output
208
+ masked_rgba = cv2.cvtColor(final_rgb, cv2.COLOR_BGR2BGRA)
209
+ masked_rgba[:, :, 3] = contracted_alpha # Use the contracted alpha (before inversion)
210
 
211
  # Create output directories if they don't exist
212
  os.makedirs(os.path.dirname(fgr_output_path), exist_ok=True)
213
  os.makedirs(os.path.dirname(masked_output_path), exist_ok=True)
214
 
215
  # Save the processed RGB image (without alpha)
216
+ success_fgr = cv2.imwrite(fgr_output_path, final_rgb)
217
  if not success_fgr:
218
  print(f"Error: Could not save RGB image to {fgr_output_path}")
219
  return False
 
269
  help="Number of pixels to contract alpha channel (default: 1)")
270
  parser.add_argument("--minimum-radius", type=int, default=4,
271
  help="Radius for minimum filter operation (default: 4)")
272
+ parser.add_argument("--blur-sigma", type=float, default=0.5,
273
+ help="Gaussian blur sigma for boundary smoothing (default: 0.5)")
274
  parser.add_argument("--sample", type=str, default=None,
275
  help="Process only specific sample (e.g., 'sample-000')")
276
 
 
301
  for i, (expanded_path, automatte_path, fgr_output_path, masked_output_path) in enumerate(pairs):
302
  print(f"Processing {i+1}/{len(pairs)}: {os.path.basename(fgr_output_path)}")
303
 
304
+ if process_foreground_correction(expanded_path, automatte_path, fgr_output_path, masked_output_path,
305
+ threshold=args.threshold,
306
+ contract_pixels=args.contract_pixels,
307
+ minimum_radius=args.minimum_radius,
308
+ blur_sigma=args.blur_sigma):
309
  successful += 1
310
  else:
311
  failed += 1