| import json |
| import os |
| import numpy as np |
| from PIL import Image |
|
|
| |
| |
| JSON_PATH = os.path.join('metadata', 'mapping_file.json') |
|
|
| |
| 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') |
|
|
| |
| 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. |
| """ |
| |
| |
| starts = np.array(mask_rle[0::2], dtype=int) |
| lengths = np.array(mask_rle[1::2], dtype=int) |
| |
| |
| starts -= 1 |
| ends = starts + lengths |
| |
| |
| total_pixels = shape[0] * shape[1] |
| binary_mask = np.zeros(total_pixels, dtype=np.uint8) |
| |
| for lo, hi in zip(starts, ends): |
| |
| if lo < total_pixels: |
| binary_mask[lo : min(hi, total_pixels)] = 1 |
| |
| |
| |
| |
| 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. |
| """ |
| |
| img_array = (mask_array * 255).astype(np.uint8) |
| img = Image.fromarray(img_array) |
| img.save(save_path) |
|
|
| def main(): |
| |
| 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(): |
| |
| 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) |
| |
| |
| 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 |
| |
| 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() |