File size: 3,353 Bytes
c83afe9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import json
import os
import numpy as np
from PIL import Image

# --- Configuration Paths ---
# Path to the source mapping file
JSON_PATH = os.path.join('metadata', 'mapping_file.json')

# Root directory for output masks
BASE_OUT_DIR = os.path.join('data', 'Task_Image_Mask_raw_image')
INPAINT_DIR = os.path.join(BASE_OUT_DIR, 'inpainting_mask')
OUTPAINT_DIR = os.path.join(BASE_OUT_DIR, 'outpainting_mask')

# Ensure output directories exist
os.makedirs(INPAINT_DIR, exist_ok=True)
os.makedirs(OUTPAINT_DIR, exist_ok=True)

def rle2mask(mask_rle, shape=(512, 512)):
    """
    Convert Absolute RLE [start, length, start, length...] to a binary mask.
    
    Args:
        mask_rle (list): List of integers in [start, len, start, len] format.
        shape (tuple): (height, width) of the image.
    """
    # 1. Split the list into starts and lengths
    # Starts are at even indices [0, 2, 4...], Lengths are at odd indices [1, 3, 5...]
    starts = np.array(mask_rle[0::2], dtype=int)
    lengths = np.array(mask_rle[1::2], dtype=int)
    
    # 2. Adjust for 1-based indexing (convert to 0-based for Python)
    starts -= 1
    ends = starts + lengths
    
    # 3. Create flat array and fill mask segments
    total_pixels = shape[0] * shape[1]
    binary_mask = np.zeros(total_pixels, dtype=np.uint8)
    
    for lo, hi in zip(starts, ends):
        # Safety check for corrupted indices
        if lo < total_pixels:
            binary_mask[lo : min(hi, total_pixels)] = 1
            
    # 4. Reshape to 2D
    # IMPORTANT: Try 'C' order first. If it's still skewed, use order='F'.
    # In BrushBench, this is typically Row-major ('C').
    return binary_mask.reshape(shape, order='C')

def save_mask_as_png(mask_array, save_path):
    """
    Convert a 0/1 binary array to a 0/255 grayscale image and save as PNG.
    """
    # Map 1 to 255 (white) for visibility in standard image viewers
    img_array = (mask_array * 255).astype(np.uint8)
    img = Image.fromarray(img_array)
    img.save(save_path)

def main():
    # Verify the existence of the mapping file
    if not os.path.exists(JSON_PATH):
        print(f"Error: Could not find {JSON_PATH}")
        return

    print(f"Loading metadata from {JSON_PATH}...")
    with open(JSON_PATH, 'r', encoding='utf-8') as f:
        data = json.load(f)

    processed_count = 0
    for img_id, info in data.items():
        # 1. Process Inpainting Mask (targeted region modification)
        if 'inpainting_mask' in info:
            in_mask = rle2mask(info['inpainting_mask'])
            save_path = os.path.join(INPAINT_DIR, f"{img_id}.png")
            save_mask_as_png(in_mask, save_path)
            
        # 2. Process Outpainting Mask (edge expansion)
        if 'outpainting_mask' in info:
            out_mask = rle2mask(info['outpainting_mask'])
            save_path = os.path.join(OUTPAINT_DIR, f"{img_id}.png")
            save_mask_as_png(out_mask, save_path)
        
        processed_count += 1
        # Log progress every 100 images
        if processed_count % 100 == 0:
            print(f"Progress: {processed_count} samples processed...")
        

    print(f"\nSuccess! Total samples handled: {processed_count}")
    print(f"Inpainting masks saved to: {INPAINT_DIR}")
    print(f"Outpainting masks saved to: {OUTPAINT_DIR}")

if __name__ == "__main__":
    main()