import random
import uuid
from PIL import Image, ImageDraw
# Constants for image and rectangle dimensions
IMAGE_SIZE = (2000, 2000)
RECTANGLE_SIZE = (400, 400)
GRID_SIZE = (5, 5) # Number of rectangles in rows and columns
OUTPUT_DIR = './' # Directory to save the images
for _ in range(5): # Generate 5 images
# Generate a unique run ID
run_id = uuid.uuid1()
print(f'Processing run_id: {run_id}')
# Create a blank image
image = Image.new('RGB', IMAGE_SIZE)
draw_image = ImageDraw.Draw(image)
# Calculate rectangle dimensions
rect_width, rect_height = RECTANGLE_SIZE
grid_cols, grid_rows = GRID_SIZE
# Draw the grid of rectangles with random colors
for i in range(grid_cols):
for j in range(grid_rows):
x = i * rect_width
y = j * rect_height
rectangle_shape = [
(x, y), # Top-left corner
(x + rect_width, y + rect_height) # Bottom-right corner
]
draw_image.rectangle(
rectangle_shape,
fill=(
random.randint(0, 255), # Random red
random.randint(0, 255), # Random green
random.randint(0, 255) # Random blue
)
)
# Save the generated image with the run ID as the filename
output_file = f'{OUTPUT_DIR}{run_id}.png'
image.save(output_file)
print(f'Image saved as {output_file}')
code
Generate and Save Multiple Randomly Colored Grids with Unique IDs
This Python script generates 5 unique images with grids of random-colored rectangles. Each image is created using PIL, with configurable grid and rectangle sizes. The images are saved with unique filenames based on UUIDs, making it a flexible and scalable solution for grid-based image generation.
PIL
Image processing
Random colors
Grid generation
Data visualization
Unique ID
Image saving
Looping
Procedural generation