VIOLIN / scripts /Task_Image_Mask_random_mask.py
Perkzi's picture
Update dataset to version 2
c83afe9
import json
from PIL import Image
import cv2
import numpy as np
import random
import os
JSON_PATH = os.path.join('metadata', 'mapping_file.json')
BASE_OUT_DIR = os.path.join('data', 'Task_Image_Mask_raw_image')
RANDOM_DIR = os.path.join(BASE_OUT_DIR, 'random_mask')
os.makedirs(RANDOM_DIR, exist_ok=True)
def generate_random_mask(shape=(512, 512), min_area_ratio=0.03, max_area_ratio=0.3):
"""
Generates a random geometric mask where the shape interior is BLACK (0)
and the background is WHITE (255).
"""
h, w = shape
total_area = h * w
# Target area for the shape (the black part)
target_area = random.uniform(total_area * min_area_ratio, total_area * max_area_ratio)
# Pick a random shape type
shape_type = random.choice(["rectangle", "triangle", "ellipse"])
# Initialize with 255 (White - Area to keep)
mask = np.full((h, w), 255, dtype=np.uint8)
if shape_type == "rectangle":
aspect = random.uniform(0.5, 2.0)
sw = int(np.sqrt(target_area * aspect))
sh = int(target_area / sw)
radius = int(np.sqrt(sw**2 + sh**2) / 2) + 5
cx, cy = get_safe_center(h, w, radius)
angle = random.randint(0, 180)
rect = ((cx, cy), (sw, sh), angle)
box = cv2.boxPoints(rect)
# Draw the shape in 0 (Black - Area to modify)
cv2.fillPoly(mask, [np.int0(box)], 0)
elif shape_type == "ellipse":
aspect = random.uniform(0.5, 2.0)
semi_a = int(np.sqrt((target_area / np.pi) * aspect))
semi_b = int((target_area / np.pi) / semi_a)
radius = max(semi_a, semi_b) + 5
cx, cy = get_safe_center(h, w, radius)
angle = random.randint(0, 360)
cv2.ellipse(mask, (cx, cy), (semi_a, semi_b), angle, 0, 360, 0, -1)
elif shape_type == "triangle":
# Using circumradius to control area:
R = int(np.sqrt(target_area / 1.299))
# R = int(np.sqrt(target_area / 1.0))
radius = R + 5
cx, cy = get_safe_center(h, w, radius)
base_angles = [0, 120, 240]
angles = [np.deg2rad(a + random.randint(-25, 25)) for a in base_angles]
pts = np.array([
[cx + R * np.cos(a), cy + R * np.sin(a)] for a in angles
], np.int32)
cv2.fillPoly(mask, [pts], 0)
return mask
def get_safe_center(h, w, radius):
"""
Returns a random (cx, cy) that ensures a circle of 'radius' fits in the image.
"""
pad = radius + 5
# Defensive check if radius is too large for the image
safe_h = max(pad, h - pad)
safe_w = max(pad, w - pad)
cx = random.randint(min(pad, safe_w), max(pad, safe_w))
cy = random.randint(min(pad, safe_h), max(pad, safe_h))
return cx, cy
def main():
if not os.path.exists(JSON_PATH):
print(f"Error: {JSON_PATH} not found.")
return
print(f"Loading metadata...")
with open(JSON_PATH, 'r', encoding='utf-8') as f:
data = json.load(f)
count = 0
for img_id, info in data.items():
# Get dimensions if available, else default to 512
h = info.get('height', 512)
w = info.get('width', 512)
img_shape = (h, w)
# 3. Generate a brand new Random Mask
rand_mask = generate_random_mask(shape=img_shape)
cv2.imwrite(os.path.join(RANDOM_DIR, f"{img_id}.png"), rand_mask)
count += 1
if count % 100 == 0:
print(f"Processed {count} images...")
print(f"\nDone! Successfully processed {count} samples.")
if __name__ == "__main__":
random.seed(42)
main()