| |
|
| | import csv |
| | import os |
| | from PIL import Image |
| |
|
| | def normalize_hex(hex_color: str) -> str: |
| | """Make sure the hex color starts with #""" |
| | if not hex_color: |
| | return "#000000" |
| | hex_color = hex_color.strip() |
| | return hex_color if hex_color.startswith("#") else f"#{hex_color}" |
| |
|
| | def replace_placeholders(prompt: str, row: dict) -> str: |
| | """Replace the placeholder in prompt""" |
| | color_format = row.get("color_format", "").strip() or "Hex code" |
| | mapping = { |
| | "<color_format>": color_format, |
| | "<color_1>": normalize_hex(row.get("color_1", "")), |
| | "<color_2>": normalize_hex(row.get("color_2", "")), |
| | "<color_3>": normalize_hex(row.get("color_3", "")), |
| | "<color_4>": normalize_hex(row.get("color_4", "")), |
| | } |
| | out = prompt |
| | for k, v in mapping.items(): |
| | if k in out and v: |
| | out = out.replace(k, v) |
| | return out |
| |
|
| | def generate_four_color_images_with_split(csv_file, base_dir, size=(256, 256)): |
| | with open(csv_file, "r", encoding="utf-8") as f: |
| | reader = csv.DictReader(f) |
| | rows = list(reader) |
| |
|
| | for row in rows: |
| | id_val = row["id"].strip() |
| | hex1 = normalize_hex(row.get("color_1", "")) |
| | hex2 = normalize_hex(row.get("color_2", "")) |
| | hex3 = normalize_hex(row.get("color_3", "")) |
| | hex4 = normalize_hex(row.get("color_4", "")) |
| | prompt_raw = row.get("prompt", "").strip() |
| | split = (row.get("split") or "train").strip() |
| |
|
| | |
| | prompt_filled = replace_placeholders(prompt_raw, row) |
| |
|
| | |
| | out_dir = base_dir |
| | os.makedirs(out_dir, exist_ok=True) |
| |
|
| | |
| | img_path = os.path.join(out_dir, f"id_{id_val}.png") |
| | txt_path = os.path.join(out_dir, f"id_{id_val}.txt") |
| |
|
| | |
| | img = Image.new("RGB", size) |
| |
|
| | |
| | tl = Image.new("RGB", (size[0] // 2, size[1] // 2), hex1) |
| | tr = Image.new("RGB", (size[0] // 2, size[1] // 2), hex2) |
| | bl = Image.new("RGB", (size[0] // 2, size[1] // 2), hex3) |
| | br = Image.new("RGB", (size[0] // 2, size[1] // 2), hex4) |
| |
|
| | |
| | img.paste(tl, (0, 0)) |
| | img.paste(tr, (size[0] // 2, 0)) |
| | img.paste(bl, (0, size[1] // 2)) |
| | img.paste(br, (size[0] // 2, size[1] // 2)) |
| |
|
| | img.save(img_path) |
| |
|
| | |
| | with open(txt_path, "w", encoding="utf-8") as f: |
| | f.write(prompt_filled) |
| |
|
| | print(f"Generate: {img_path}, {txt_path} (split={split}, colors={hex1},{hex2},{hex3},{hex4})") |
| |
|
| |
|
| | generate_four_color_images_with_split( |
| | "metadata/Variation_3_Color_1.csv", |
| | base_dir="data/Variation_3/Color_Level_1" |
| | ) |
| | generate_four_color_images_with_split( |
| | "metadata/Variation_3_Color_2.csv", |
| | base_dir="data/Variation_3/Color_Level_2" |
| | ) |
| | generate_four_color_images_with_split( |
| | "metadata/Variation_3_Color_3.csv", |
| | base_dir="data/Variation_3/Color_Level_3" |
| | ) |
| |
|