#!/usr/bin/env python3 """ Foreground Correction Script This script processes images from data/expanded/*/*.png and matching pairs from data/automatte/*/*.png to generate two types of corrected images: 1. Processed RGB images in data/fgr/*/*.png (RGB without alpha) 2. Masked RGBA images in data/masked/*/*.png (with alpha channel applied) The foreground correction process: 1. Load alpha (from automatte folder) 2. Apply thresholding (white = anything >230, black otherwise) 3. Contract the alpha channel 1px (equivalent to Select > Modify > Contract in Photoshop) 4. Invert selection to create a mask 5. Apply minimum filter with 4px radius to the RGB image using the inverted selection mask (equivalent to Filter > Other > Minimum in Photoshop) 6. Apply Gaussian blur on ±0.5 pixel region of selection mask boundaries for smooth transitions 7. Export both versions: - FGR: RGB image with the processed regions - Masked: RGBA image using the contracted alpha (before inversion) as the alpha channel """ import os import glob import cv2 import numpy as np from pathlib import Path import argparse def apply_threshold(alpha_channel, threshold=230): """Apply thresholding: white for values > threshold, black otherwise.""" _, thresholded = cv2.threshold(alpha_channel, threshold, 255, cv2.THRESH_BINARY) return thresholded def contract_alpha(alpha_channel, pixels=1): """Contract the alpha channel by specified pixels (erosion operation).""" kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*pixels+1, 2*pixels+1)) contracted = cv2.erode(alpha_channel, kernel, iterations=1) return contracted def invert_selection(alpha_channel): """Invert the selection (white becomes black, black becomes white).""" return cv2.bitwise_not(alpha_channel) def apply_minimum_filter(alpha_channel, radius=4): """Apply minimum filter with specified radius (erosion operation).""" kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*radius+1, 2*radius+1)) filtered = cv2.erode(alpha_channel, kernel, iterations=1) return filtered def apply_minimum_filter_to_rgb(rgb_image, mask, radius=4, method='erosion'): """ Apply minimum filter to RGB image using a mask selection. Only pixels where mask is white (255) will be affected. Args: rgb_image: Input RGB image mask: Binary mask (white = process, black = leave unchanged) radius: Filter radius in pixels method: 'erosion' (standard), 'radial' (distance-based), 'opening', 'closing' """ filtered_rgb = rgb_image.copy() mask_binary = (mask == 255).astype(np.uint8) if method == 'radial': # Distance transform based radial approach return apply_radial_filter_to_rgb(rgb_image, mask, radius) elif method == 'opening': # Morphological opening (erosion + dilation) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*radius+1, 2*radius+1)) for channel in range(3): opened_channel = cv2.morphologyEx(rgb_image[:, :, channel], cv2.MORPH_OPEN, kernel) filtered_rgb[:, :, channel] = np.where(mask_binary, opened_channel, rgb_image[:, :, channel]) elif method == 'closing': # Morphological closing (dilation + erosion) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*radius+1, 2*radius+1)) for channel in range(3): closed_channel = cv2.morphologyEx(rgb_image[:, :, channel], cv2.MORPH_CLOSE, kernel) filtered_rgb[:, :, channel] = np.where(mask_binary, closed_channel, rgb_image[:, :, channel]) else: # 'erosion' (default) # Standard erosion (minimum filter) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*radius+1, 2*radius+1)) for channel in range(3): eroded_channel = cv2.erode(rgb_image[:, :, channel], kernel, iterations=1) filtered_rgb[:, :, channel] = np.where(mask_binary, eroded_channel, rgb_image[:, :, channel]) return filtered_rgb def apply_radial_filter_to_rgb(rgb_image, mask, radius=4): """ Apply radial minimum filter using distance transform. This method works more radially than standard morphological erosion. """ filtered_rgb = rgb_image.copy() mask_binary = (mask == 255).astype(np.uint8) # Create distance transform of the mask dist_transform = cv2.distanceTransform(mask_binary, cv2.DIST_L2, 5) # Create a radial kernel based on distance height, width = rgb_image.shape[:2] y, x = np.ogrid[:height, :width] for channel in range(3): channel_data = rgb_image[:, :, channel].astype(np.float32) filtered_channel = channel_data.copy() # For each pixel in the mask, find minimum in radial neighborhood mask_coords = np.where(mask_binary > 0) for my, mx in zip(mask_coords[0], mask_coords[1]): # Create circular mask around current pixel distances = np.sqrt((y - my)**2 + (x - mx)**2) circle_mask = distances <= radius # Find minimum value in the circular neighborhood if np.any(circle_mask): min_val = np.min(channel_data[circle_mask]) filtered_channel[my, mx] = min_val filtered_rgb[:, :, channel] = filtered_channel.astype(np.uint8) return filtered_rgb def create_boundary_mask(mask, boundary_width=1): """ Create a boundary mask that covers the edge region of the given mask. Args: mask: Binary mask (0 or 255) boundary_width: Width of the boundary region in pixels (default: 1 for ±0.5 pixels) Returns: Boundary mask where boundaries are white (255) """ # Create kernels for dilation and erosion kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*boundary_width+1, 2*boundary_width+1)) # Dilate and erode the mask to find boundaries dilated = cv2.dilate(mask, kernel, iterations=1) eroded = cv2.erode(mask, kernel, iterations=1) # Boundary is the difference between dilated and eroded versions boundary = cv2.subtract(dilated, eroded) return boundary def apply_boundary_blur(rgb_image, boundary_mask, blur_sigma=0.5): """ Apply Gaussian blur to the RGB image only in the boundary regions. Args: rgb_image: Input RGB image boundary_mask: Binary mask indicating boundary regions blur_sigma: Gaussian blur sigma value Returns: RGB image with blurred boundaries """ # Convert sigma to kernel size (OpenCV uses kernel size, not sigma directly) # Rule of thumb: kernel_size = 2 * int(3 * sigma) + 1 kernel_size = 2 * int(3 * blur_sigma) + 1 if kernel_size < 3: kernel_size = 3 # Make sure kernel size is odd if kernel_size % 2 == 0: kernel_size += 1 # Apply Gaussian blur to the entire image blurred_rgb = cv2.GaussianBlur(rgb_image, (kernel_size, kernel_size), blur_sigma) # Create a normalized boundary mask (0.0 to 1.0) boundary_mask_norm = (boundary_mask > 0).astype(np.float32) # Blend the original and blurred images based on the boundary mask result = rgb_image.copy().astype(np.float32) for channel in range(3): result[:, :, channel] = (1.0 - boundary_mask_norm) * rgb_image[:, :, channel].astype(np.float32) + \ boundary_mask_norm * blurred_rgb[:, :, channel].astype(np.float32) return result.astype(np.uint8) def process_foreground_correction(expanded_path, automatte_path, fgr_output_path, masked_output_path, threshold=230, contract_pixels=1, minimum_radius=2, blur_sigma=0.5, filter_method='erosion'): """ Process a single image pair for foreground correction. Args: expanded_path: Path to the expanded image automatte_path: Path to the automatte (alpha) image fgr_output_path: Path where the processed RGB image will be saved masked_output_path: Path where the masked RGBA image will be saved threshold: Threshold value for alpha binarization contract_pixels: Number of pixels to contract alpha channel minimum_radius: Radius for minimum filter operation blur_sigma: Gaussian blur sigma for boundary smoothing filter_method: Method for minimum filter ('erosion', 'radial', 'opening', 'closing') """ # Load the expanded image (RGB) expanded_img = cv2.imread(expanded_path, cv2.IMREAD_COLOR) if expanded_img is None: print(f"Error: Could not load expanded image: {expanded_path}") return False # Load the automatte image (alpha channel) automatte_img = cv2.imread(automatte_path, cv2.IMREAD_GRAYSCALE) if automatte_img is None: print(f"Error: Could not load automatte image: {automatte_path}") return False # Ensure both images have the same dimensions if expanded_img.shape[:2] != automatte_img.shape[:2]: print(f"Warning: Size mismatch between {expanded_path} and {automatte_path}") # Resize automatte to match expanded image automatte_img = cv2.resize(automatte_img, (expanded_img.shape[1], expanded_img.shape[0])) # Step 1: Alpha channel is already loaded from automatte alpha = automatte_img.copy() # Step 2: Apply thresholding (white = anything >threshold, black otherwise) thresholded_alpha = apply_threshold(alpha, threshold=threshold) # Step 3: Contract the alpha channel contracted_alpha = contract_alpha(thresholded_alpha, pixels=contract_pixels) # Step 4: Invert selection selection_mask = invert_selection(contracted_alpha) # Step 5: Apply minimum filter to RGB image using the selection mask filtered_rgb = apply_minimum_filter_to_rgb(expanded_img, selection_mask, radius=minimum_radius, method=filter_method) # Step 6: Apply Gaussian blur on ±0.5 region of selection mask boundaries boundary_mask = create_boundary_mask(selection_mask, boundary_width=1) final_rgb = apply_boundary_blur(filtered_rgb, boundary_mask, blur_sigma=blur_sigma) # # DO NOT COMMIT: save alpha and exit # cv2.imwrite("debug/debug_expanded.png", expanded_img) # cv2.imwrite("debug/debug_automatte.png", automatte_img) # cv2.imwrite("debug/debug_alpha.png", alpha) # cv2.imwrite("debug/debug_thresholded_alpha.png", thresholded_alpha) # cv2.imwrite("debug/debug_contracted_alpha.png", contracted_alpha) # cv2.imwrite("debug/debug_selection_mask.png", selection_mask) # cv2.imwrite("debug/debug_filtered_rgb.png", filtered_rgb) # cv2.imwrite("debug/debug_final_rgb.png", final_rgb) # Apply the original contracted alpha (before inversion) to the final RGB image # Convert to RGBA for masked output masked_rgba = cv2.cvtColor(final_rgb, cv2.COLOR_BGR2BGRA) masked_rgba[:, :, 3] = alpha # Use predicted alpha # Create output directories if they don't exist os.makedirs(os.path.dirname(fgr_output_path), exist_ok=True) os.makedirs(os.path.dirname(masked_output_path), exist_ok=True) # Save the processed RGB image (without alpha) success_fgr = cv2.imwrite(fgr_output_path, final_rgb) if not success_fgr: print(f"Error: Could not save RGB image to {fgr_output_path}") return False # Save the masked RGBA image (with alpha channel) success_masked = cv2.imwrite(masked_output_path, masked_rgba) if not success_masked: print(f"Error: Could not save masked image to {masked_output_path}") return False return True def find_matching_pairs(): """Find all matching pairs between expanded and automatte folders.""" expanded_base = "data/expanded" automatte_base = "data/automatte" pairs = [] # Get all PNG files in expanded folders expanded_pattern = os.path.join(expanded_base, "*", "*.png") expanded_files = glob.glob(expanded_pattern) # Sort the expanded files to ensure consistent processing order expanded_files.sort() for expanded_path in expanded_files: # Extract relative path from expanded base rel_path = os.path.relpath(expanded_path, expanded_base) # Construct corresponding automatte path automatte_path = os.path.join(automatte_base, rel_path) # Check if the automatte file exists if os.path.exists(automatte_path): # Construct output paths for both fgr and masked fgr_output_path = os.path.join("data/fgr", rel_path) masked_output_path = os.path.join("data/masked", rel_path) pairs.append((expanded_path, automatte_path, fgr_output_path, masked_output_path)) else: print(f"Warning: No matching automatte file for {expanded_path}") return pairs def main(): """Main function to process all image pairs.""" parser = argparse.ArgumentParser(description="Apply foreground correction to image pairs") parser.add_argument("--threshold", type=int, default=230, help="Threshold value for alpha binarization (default: 230)") parser.add_argument("--contract-pixels", type=int, default=1, help="Number of pixels to contract alpha channel (default: 1)") parser.add_argument("--minimum-radius", type=int, default=50, help="Radius for minimum filter operation (default: 3)") parser.add_argument("--blur-sigma", type=float, default=0.5, help="Gaussian blur sigma for boundary smoothing (default: 0.5)") parser.add_argument("--filter-method", type=str, default="erosion", choices=["erosion", "radial", "opening", "closing"], help="Method for minimum filter (default: erosion). 'radial' works more radially.") parser.add_argument("--sample", type=str, default=None, help="Process only specific sample (e.g., 'sample-000')") args = parser.parse_args() # Find all matching pairs pairs = find_matching_pairs() if not pairs: print("No matching pairs found!") return # Filter by sample if specified if args.sample: pairs = [p for p in pairs if args.sample in p[0]] print(f"Processing {len(pairs)} files for {args.sample}") else: print(f"Found {len(pairs)} matching pairs to process") # Create output base directories os.makedirs("data/fgr", exist_ok=True) os.makedirs("data/masked", exist_ok=True) # Process each pair successful = 0 failed = 0 for i, (expanded_path, automatte_path, fgr_output_path, masked_output_path) in enumerate(pairs): print(f"Processing {i+1}/{len(pairs)}: {os.path.basename(fgr_output_path)}") if process_foreground_correction(expanded_path, automatte_path, fgr_output_path, masked_output_path, threshold=args.threshold, contract_pixels=args.contract_pixels, minimum_radius=args.minimum_radius, blur_sigma=args.blur_sigma, filter_method=args.filter_method): successful += 1 else: failed += 1 print(f"\nProcessing complete!") print(f"Successful: {successful}") print(f"Failed: {failed}") print(f"Total: {len(pairs)}") if __name__ == "__main__": main()