Datasets:
File size: 2,998 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
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", "")),
}
out = prompt
for k, v in mapping.items():
if k in out and v:
out = out.replace(k, v)
return out
def generate_two_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", ""))
prompt_raw = row.get("prompt", "").strip()
split = (row.get("split") or "train").strip()
direction = row.get("direction", "").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)
# file path
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 drawing
img = Image.new("RGB", size)
# direction
if direction=="h": # horizontal Top and bottom split
top = Image.new("RGB", (size[0], size[1] // 2), hex1)
bottom = Image.new("RGB", (size[0], size[1] // 2), hex2)
img.paste(top, (0, 0))
img.paste(bottom, (0, size[1] // 2))
elif direction=="v": # vertical Left and right split
left = Image.new("RGB", (size[0] // 2, size[1]), hex1)
right = Image.new("RGB", (size[0] // 2, size[1]), hex2)
img.paste(left, (0, 0))
img.paste(right, (size[0] // 2, 0))
else:
img = Image.new("RGB", size, hex1)
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}, colors={hex1},{hex2})")
generate_two_color_images_with_split(
"metadata/Variation_2_Color_1.csv",
base_dir="data/Variation_2/Color_Level_1"
)
generate_two_color_images_with_split(
"metadata/Variation_2_Color_2.csv",
base_dir="data/Variation_2/Color_Level_2"
)
generate_two_color_images_with_split(
"metadata/Variation_2_Color_3.csv",
base_dir="data/Variation_2/Color_Level_3"
)
|