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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Foreground Correction Script
|
| 4 |
+
|
| 5 |
+
This script processes images from data/expanded/*/*.png and matching pairs
|
| 6 |
+
from data/automatte/*/*.png to generate corrected foreground images in
|
| 7 |
+
data/fgr/*/*.png with the same names.
|
| 8 |
+
|
| 9 |
+
The foreground correction process:
|
| 10 |
+
1. Load alpha (from automatte folder)
|
| 11 |
+
2. Apply thresholding (white = anything >253, black otherwise)
|
| 12 |
+
3. Contract the alpha channel 1px (equivalent to Select > Modify > Contract in Photoshop)
|
| 13 |
+
4. Invert selection to create a mask
|
| 14 |
+
5. Apply minimum filter with 4px radius to the RGB image using the inverted selection mask
|
| 15 |
+
(equivalent to Filter > Other > Minimum in Photoshop)
|
| 16 |
+
6. Use the contracted alpha (before inversion) as the final alpha channel
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import glob
|
| 21 |
+
import cv2
|
| 22 |
+
import numpy as np
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
import argparse
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def apply_threshold(alpha_channel, threshold=253):
|
| 28 |
+
"""Apply thresholding: white for values > threshold, black otherwise."""
|
| 29 |
+
_, thresholded = cv2.threshold(alpha_channel, threshold, 255, cv2.THRESH_BINARY)
|
| 30 |
+
return thresholded
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def contract_alpha(alpha_channel, pixels=1):
|
| 34 |
+
"""Contract the alpha channel by specified pixels (erosion operation)."""
|
| 35 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*pixels+1, 2*pixels+1))
|
| 36 |
+
contracted = cv2.erode(alpha_channel, kernel, iterations=1)
|
| 37 |
+
return contracted
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def invert_selection(alpha_channel):
|
| 41 |
+
"""Invert the selection (white becomes black, black becomes white)."""
|
| 42 |
+
return cv2.bitwise_not(alpha_channel)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def apply_minimum_filter(alpha_channel, radius=4):
|
| 46 |
+
"""Apply minimum filter with specified radius (erosion operation)."""
|
| 47 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*radius+1, 2*radius+1))
|
| 48 |
+
filtered = cv2.erode(alpha_channel, kernel, iterations=1)
|
| 49 |
+
return filtered
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def apply_minimum_filter_to_rgb(rgb_image, mask, radius=4):
|
| 53 |
+
"""
|
| 54 |
+
Apply minimum filter to RGB image using a mask selection.
|
| 55 |
+
Only pixels where mask is white (255) will be affected.
|
| 56 |
+
"""
|
| 57 |
+
# Create kernel for minimum filter
|
| 58 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*radius+1, 2*radius+1))
|
| 59 |
+
|
| 60 |
+
# Apply erosion (minimum filter) to each color channel
|
| 61 |
+
filtered_rgb = rgb_image.copy()
|
| 62 |
+
|
| 63 |
+
# Only apply filter where mask is white (255)
|
| 64 |
+
mask_binary = (mask == 255).astype(np.uint8)
|
| 65 |
+
|
| 66 |
+
for channel in range(3): # B, G, R channels
|
| 67 |
+
# Apply erosion to the channel
|
| 68 |
+
eroded_channel = cv2.erode(rgb_image[:, :, channel], kernel, iterations=1)
|
| 69 |
+
|
| 70 |
+
# Use the mask to selectively apply the filtered result
|
| 71 |
+
filtered_rgb[:, :, channel] = np.where(mask_binary,
|
| 72 |
+
eroded_channel,
|
| 73 |
+
rgb_image[:, :, channel])
|
| 74 |
+
|
| 75 |
+
return filtered_rgb
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def process_foreground_correction(expanded_path, automatte_path, output_path):
|
| 79 |
+
"""
|
| 80 |
+
Process a single image pair for foreground correction.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
expanded_path: Path to the expanded image
|
| 84 |
+
automatte_path: Path to the automatte (alpha) image
|
| 85 |
+
output_path: Path where the corrected image will be saved
|
| 86 |
+
"""
|
| 87 |
+
# Load the expanded image (RGB)
|
| 88 |
+
expanded_img = cv2.imread(expanded_path, cv2.IMREAD_COLOR)
|
| 89 |
+
if expanded_img is None:
|
| 90 |
+
print(f"Error: Could not load expanded image: {expanded_path}")
|
| 91 |
+
return False
|
| 92 |
+
|
| 93 |
+
# Load the automatte image (alpha channel)
|
| 94 |
+
automatte_img = cv2.imread(automatte_path, cv2.IMREAD_GRAYSCALE)
|
| 95 |
+
if automatte_img is None:
|
| 96 |
+
print(f"Error: Could not load automatte image: {automatte_path}")
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
# Ensure both images have the same dimensions
|
| 100 |
+
if expanded_img.shape[:2] != automatte_img.shape[:2]:
|
| 101 |
+
print(f"Warning: Size mismatch between {expanded_path} and {automatte_path}")
|
| 102 |
+
# Resize automatte to match expanded image
|
| 103 |
+
automatte_img = cv2.resize(automatte_img, (expanded_img.shape[1], expanded_img.shape[0]))
|
| 104 |
+
|
| 105 |
+
# Step 1: Alpha channel is already loaded from automatte
|
| 106 |
+
alpha = automatte_img.copy()
|
| 107 |
+
|
| 108 |
+
# Step 2: Apply thresholding (white = anything >253, black otherwise)
|
| 109 |
+
thresholded_alpha = apply_threshold(alpha, threshold=253)
|
| 110 |
+
|
| 111 |
+
# # DO NOT COMMIT: save alpha and exit
|
| 112 |
+
# cv2.imwrite("debug_alpha.png", alpha)
|
| 113 |
+
# import sys; sys.exit(0)
|
| 114 |
+
|
| 115 |
+
# Step 3: Contract the alpha channel 1px
|
| 116 |
+
contracted_alpha = contract_alpha(thresholded_alpha, pixels=1)
|
| 117 |
+
|
| 118 |
+
# # DO NOT COMMIT: save alpha and exit
|
| 119 |
+
# cv2.imwrite("debug_contracted_alpha.png", alpha)
|
| 120 |
+
# import sys; sys.exit(0)
|
| 121 |
+
|
| 122 |
+
# Step 4: Invert selection
|
| 123 |
+
selection_mask = invert_selection(contracted_alpha)
|
| 124 |
+
|
| 125 |
+
# # DO NOT COMMIT: save alpha and exit
|
| 126 |
+
# cv2.imwrite("debug_inverted_alpha.png", selection_mask)
|
| 127 |
+
# import sys; sys.exit(0)
|
| 128 |
+
|
| 129 |
+
# Step 5: Apply minimum filter to RGB image using the selection mask
|
| 130 |
+
filtered_rgb = apply_minimum_filter_to_rgb(expanded_img, selection_mask, radius=4)
|
| 131 |
+
|
| 132 |
+
# Apply the original contracted alpha (before inversion) to the filtered RGB image
|
| 133 |
+
# Convert to RGBA
|
| 134 |
+
expanded_rgba = cv2.cvtColor(filtered_rgb, cv2.COLOR_BGR2BGRA)
|
| 135 |
+
expanded_rgba[:, :, 3] = alpha # Use the contracted alpha (before inversion)
|
| 136 |
+
|
| 137 |
+
# Create output directory if it doesn't exist
|
| 138 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 139 |
+
|
| 140 |
+
# Save the result
|
| 141 |
+
success = cv2.imwrite(output_path, filtered_rgb)
|
| 142 |
+
if not success:
|
| 143 |
+
print(f"Error: Could not save image to {output_path}")
|
| 144 |
+
return False
|
| 145 |
+
|
| 146 |
+
return True
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def find_matching_pairs():
|
| 150 |
+
"""Find all matching pairs between expanded and automatte folders."""
|
| 151 |
+
expanded_base = "data/expanded"
|
| 152 |
+
automatte_base = "data/automatte"
|
| 153 |
+
|
| 154 |
+
pairs = []
|
| 155 |
+
|
| 156 |
+
# Get all PNG files in expanded folders
|
| 157 |
+
expanded_pattern = os.path.join(expanded_base, "*", "*.png")
|
| 158 |
+
expanded_files = glob.glob(expanded_pattern)
|
| 159 |
+
|
| 160 |
+
for expanded_path in expanded_files:
|
| 161 |
+
# Extract relative path from expanded base
|
| 162 |
+
rel_path = os.path.relpath(expanded_path, expanded_base)
|
| 163 |
+
|
| 164 |
+
# Construct corresponding automatte path
|
| 165 |
+
automatte_path = os.path.join(automatte_base, rel_path)
|
| 166 |
+
|
| 167 |
+
# Check if the automatte file exists
|
| 168 |
+
if os.path.exists(automatte_path):
|
| 169 |
+
# Construct output path
|
| 170 |
+
output_path = os.path.join("data/fgr", rel_path)
|
| 171 |
+
pairs.append((expanded_path, automatte_path, output_path))
|
| 172 |
+
else:
|
| 173 |
+
print(f"Warning: No matching automatte file for {expanded_path}")
|
| 174 |
+
|
| 175 |
+
return pairs
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def main():
|
| 179 |
+
"""Main function to process all image pairs."""
|
| 180 |
+
parser = argparse.ArgumentParser(description="Apply foreground correction to image pairs")
|
| 181 |
+
parser.add_argument("--threshold", type=int, default=253,
|
| 182 |
+
help="Threshold value for alpha binarization (default: 253)")
|
| 183 |
+
parser.add_argument("--contract-pixels", type=int, default=1,
|
| 184 |
+
help="Number of pixels to contract alpha channel (default: 1)")
|
| 185 |
+
parser.add_argument("--minimum-radius", type=int, default=4,
|
| 186 |
+
help="Radius for minimum filter operation (default: 4)")
|
| 187 |
+
parser.add_argument("--sample", type=str, default=None,
|
| 188 |
+
help="Process only specific sample (e.g., 'sample-000')")
|
| 189 |
+
|
| 190 |
+
args = parser.parse_args()
|
| 191 |
+
|
| 192 |
+
# Find all matching pairs
|
| 193 |
+
pairs = find_matching_pairs()
|
| 194 |
+
|
| 195 |
+
if not pairs:
|
| 196 |
+
print("No matching pairs found!")
|
| 197 |
+
return
|
| 198 |
+
|
| 199 |
+
# Filter by sample if specified
|
| 200 |
+
if args.sample:
|
| 201 |
+
pairs = [p for p in pairs if args.sample in p[0]]
|
| 202 |
+
print(f"Processing {len(pairs)} files for {args.sample}")
|
| 203 |
+
else:
|
| 204 |
+
print(f"Found {len(pairs)} matching pairs to process")
|
| 205 |
+
|
| 206 |
+
# Create output base directory
|
| 207 |
+
os.makedirs("data/fgr", exist_ok=True)
|
| 208 |
+
|
| 209 |
+
# Process each pair
|
| 210 |
+
successful = 0
|
| 211 |
+
failed = 0
|
| 212 |
+
|
| 213 |
+
for i, (expanded_path, automatte_path, output_path) in enumerate(pairs):
|
| 214 |
+
print(f"Processing {i+1}/{len(pairs)}: {os.path.basename(output_path)}")
|
| 215 |
+
|
| 216 |
+
if process_foreground_correction(expanded_path, automatte_path, output_path):
|
| 217 |
+
successful += 1
|
| 218 |
+
else:
|
| 219 |
+
failed += 1
|
| 220 |
+
|
| 221 |
+
print(f"\nProcessing complete!")
|
| 222 |
+
print(f"Successful: {successful}")
|
| 223 |
+
print(f"Failed: {failed}")
|
| 224 |
+
print(f"Total: {len(pairs)}")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
main()
|