Datasets:
File size: 2,335 Bytes
5e1ef3a | 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 | 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_images_and_prompts_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()
hex_color = normalize_hex(row.get("color_1", ""))
prompt_raw = row.get("prompt", "").strip()
split = (row.get("split") or "train").strip()
# Replace the placeholder in prompt
prompt_filled = replace_placeholders(prompt_raw, row)
# out_dir = os.path.join(base_dir, split)
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")
# Create a blank image
img = Image.new("RGB", size, hex_color)
img.save(img_path)
# write prompt
with open(txt_path, "w", encoding="utf-8") as f:
f.write(prompt_filled)
# print(f"Generate: {img_path}, {txt_path} (split={split})")
generate_images_and_prompts_with_split(
"metadata/Variation_5_Color_1.csv",
base_dir="data/Variation_5/Color_Level_1"
)
generate_images_and_prompts_with_split(
"metadata/Variation_5_Color_2.csv",
base_dir="data/Variation_5/Color_Level_2"
)
generate_images_and_prompts_with_split(
"metadata/Variation_5_Color_3.csv",
base_dir="data/Variation_5/Color_Level_3"
)
|