Generative Art in Python with PIL
Date: 2021-06-13 | art | python | generative-art |
In this post we go over what generative art is and how to create it using Python.
Generative Art
Generative art (also known as procedural art) combines rules with inputs to produce near infinite output combinations. An example of this practice would be to randomly select values for the following attributes:
- color
- size
- location
Just these few variables net us with color x size x location potential outputs. It's easy to imagine more: orientation, shape, 2d / 3d etc.
I like to leverage code in my generative art practice due to its scalability, consistency, and flexibility. Whereas a single human would take a long time to draw / shape / model / etc all color x size x location outputs, we can imagine that code could output these much faster (and also that the computer won't get bored and start complaining).
Some generative art:
Generative Art with Python
Today we'll be generating n squares of varying colors in different locations on an image. We'll then store that image somewhere for later retrieval.
The code:
import random
import uuid
from PIL import Image, ImageDraw
run_id = uuid.uuid1()
print(f'Processing run_id: {run_id}')
image = Image.new('RGB', (2000, 2000))
width, height = image.size
rectangle_width = 100
rectangle_height = 100
number_of_squares = random.randint(10, 550)
draw_image = ImageDraw.Draw(image)
for i in range(number_of_squares):
rectangle_x = random.randint(0, width)
rectangle_y = random.randint(0, height)
rectangle_shape = [
(rectangle_x, rectangle_y),
(rectangle_x + rectangle_width, rectangle_y + rectangle_height)]
draw_image.rectangle(
rectangle_shape,
fill=(
random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255)
)
)
image.save(f'./output/{run_id}.png')
Code walkthrough:
- First we import the Python-native random and uuid libraries we'll use in the script
- Then we import some libraries from PIL - a well-supported, documented, and powerful image manipulation library for Python
- We then create an image, set some bounds for our generation, and determine how many squares we want to draw
- For each square we want to draw, we find a location and set a color
- We finish up by saving the image to our file system
Want more like this?
The best / easiest way to support my work is by subscribing for future updates and sharing with your network.